MathGroup Archive 2005

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

Search the Archive

Re: Tilting at Windmills?

  • To: mathgroup at
  • Subject: [mg62150] Re: Tilting at Windmills?
  • From: Bill Rowe <readnewsciv at>
  • Date: Sat, 12 Nov 2005 03:33:04 -0500 (EST)
  • Sender: owner-wri-mathgroup at

On 11/11/05 at 2:52 AM, anonmous69 at (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
>xn-1,xn-1,xn} which will then need to be partitioned to end up in
>the following form:
>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}]
{{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]; 
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]}]]


In[20]:=h[data] == f[data]

Out[21]=0.11 Second
To reply via email subtract one hundred and four

  • Prev by Date: Re: Re: Re: integer solution
  • Next by Date: Re: Re: Plot Angle between Vectors
  • Previous by thread: Re: Tilting at Windmills?
  • Next by thread: Re: Tilting at Windmills?