MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: List manipulation question

  • To: mathgroup at smc.vnet.net
  • Subject: [mg67209] Re: List manipulation question
  • From: "dkr" <dkrjeg at adelphia.net>
  • Date: Sun, 11 Jun 2006 23:08:50 -0400 (EDT)
  • References: <e6ge0k$nh3$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Here is a pure pattern matching approach:

In[19]:=
list={3700, 3800, 3900, 3950, 4000, 4050, 4100, 4150, 4200, 4250, 4300,

 4350,  4400, 4450, 4500, 4550, 4600, 4650} ;

In[20]:=
Join[{dum[]},list]//.{{dum[a__],b_,c_,d_,e___}:>{dum[a,(d-b)/2],c,d,e},
{dum[],b_,c_,
        d___}:>{dum[c-b],b,c,d}, {dum[a__],b_,c_}:> {a,c-b} }
Out[20]=
{100,100,75,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50}

We first prepend a dummy container dum[] to your list.  This container
is used to store results of previous iterations of the ReplaceRepeated.
 Initially the second rule will match, with b corresponding to the
first element of list (assuming list has at least two elements).  The
rule transforms the first element appropriately, storing the result
inside dum, and returns dum along with the entire list. On the next
iteration, the first rule will take over (assuming list has at least 3
elements), with c playing the role of the second element of list. The
second element is transformed appropriately, the result added to the
args of dum, with the rule returning dum along with all the elements of
list except the first one.  The first rule will continue to match until
we get to the stage where only two elements from the original list
remain. Then the third rule will match, the appropriate transformation
will be made on the last element of the original list, and the rule
will return this result appended to the sequence of all previous
transformations.  Since dum is no longer around, the ReplaceRepeated
iteration will end.

Instead of using a dummy storage container, and having separate rules
to handle the transformation of the first and last elements of list, we
could simply handle the first and last elements of list separately, and
use Sow and a one rule ReplaceRepeated procedure as illustrated below:

In[22]:=
transformedFirstElement=list[[2]]-list[[1]];
transformedLastElement=Last[list]-list[[-2]];
transformedIntermediateElements=
    Reap[list//.{a_,b_,c_,d___}:>(Sow[(c-a)/2];{b,c,d})][[2,1]];

In[25]:=
result=Join[{transformedFirstElement},
    transformedIntermediateElements,{transformedLastElement}]
Out[25]=
{100,100,75,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50}

dkr


  • Prev by Date: Re: structure array equivalent in Mathematica
  • Next by Date: Mathematica Style Sheets
  • Previous by thread: Re: List manipulation question
  • Next by thread: Re: List manipulation question