Re: Tilting at Windmills?
- To: mathgroup at smc.vnet.net
- Subject: [mg62150] Re: Tilting at Windmills?
- From: Bill Rowe <readnewsciv at earthlink.net>
- Date: Sat, 12 Nov 2005 03:33:04 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
On 11/11/05 at 2:52 AM, anonmous69 at netscape.net (Matt) wrote: >Where there's a chance of success, I tend to agonize over details of >implementation. Memory usage is one such area. Here is a >statement of a problem I was trying to solve in Mathematica: >Given a list of the following form:{x1,x2,x3,...,xn-1,xn} I want to >develop an algorithm that will iterate over the input list to >produce output of the following >form:{x1,x2,x2,x2,x2,x3,x3,x3,x3,x4,x4,x4,x4,x5,...,xn-2,xn-1,xn-1, >xn-1,xn-1,xn} which will then need to be partitioned to end up in >the following form: >{{x1,x2},{x2,x2},{x2,x3},{x3,x3},{x3,x4},{x4,x4},{x4,x5},...,{xn-2, >xn-1},{xn-1,xn-1},{xn-1,xn}} which means that if I had a flattened >list of length'n' as input, then the new flattened list would have >a length of 4*(n-2)+2 >Here is my first solution to this problem, along with a test >harness for validation: <code snipped> Your code to do what you wanted seemed more complex than needed. By making use of the third aguement to Partition you can create the list you wanted with f[x_] := Partition[Flatten@Partition[x, 2, 1], 2, 1] A quick check In[12]:=f[{x1, x2, x3, x4}] Out[12]= {{x1, x2}, {x2, x2}, {x2, x3}, {x3, x3}, {x3, x4}} shows f works as desired And a check of the timing In[17]:=data = Range[200000]; In[18]:=Timing[f[data];][[1]] Out[18]=0.21 Second An alternative that runs faster but is perhaps less obvious is h[x_] := Module[ {z = Flatten@Transpose@{Most[x], Rest[x]}}, Transpose@{Most[z], Rest[z]}]] checking In[20]:=h[data] == f[data] Out[20]=True In[21]:=Timing[h[data];][[1]] Out[21]=0.11 Second -- To reply via email subtract one hundred and four