MathGroup Archive 1995

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

Search the Archive

Re: There must be a better way!

  • To: mathgroup at smc.vnet.net
  • Subject: [mg2351] Re: [mg2322] There must be a better way!
  • From: Allan Hayes <hay at haystack.demon.co.uk>
  • Date: Fri, 27 Oct 1995 01:48:49 -0400

Paul Howland <pehowland at taz.dra.hmg.gb>
>Subject: [mg2322] There must be a better way!

Asks about "repeated takes": for example given
   {A,B,C,D,E,F,G,H,I,J} and {2,3,4,1}
he wants to get
   {{A,B}, {C,D,E}, {F,G,H,I}, {J}}.

Here is one way:

TakeRepeated[l_, t_]:=
   First/@Rest[
      FoldList[Through[{Take,Drop}[#1[[2]],#2]]&, {{},l}, t]
   ]

Example:

TakeRepeated[{A,B,C,D,E,F,G,H,I,J},{2,3,4,1}]

      {{A, B}, {C, D, E}, {F, G, H, I}, {J}}

The trick is to carry enough information for each step of FoldList  
( {bite taken, part left}), and discard the unwanted parts at the  
end.

Here is the raw output from FoldList

TakeRepeatedExplain[l_, t_]:=
   FoldList[Through[{Take,Drop}[#1[[2]],#2]]&, {{},l}, t]

TakeRepeatedExplain[{A,B,C,D,E,F,G,H,I,J},{2,3,4,1}]//ColumnForm

      {{}, {A, B, C, D, E, F, G, H, I, J}}
      {{A, B}, {C, D, E, F, G, H, I, J}}
      {{C, D, E}, {F, G, H, I, J}}
      {{F, G, H, I}, {J}}
      {{J}, {}}

Allan Hayes,
hay at haystack.demon.co.uk

*****************
Begin forwarded message:

>From: <pehowland at taz.dra.hmg.gb>
>To: mathgroup at smc.vnet.net
>Subject: [mg2322] There must be a better way!
>Organization: LSC2 Division, Defence Research Agency


Hi.  I'm trying to write a function that partitions a list into
segments of length given by another length. eg.
	Given l1 = {A,B,C,D,E,F,G,H,I,J}
	and   l2 = {2,3,4,1}
I want to be able to say
	In[1] := MyPartition[l1, l2]
and get
	Out[1] = {{A,B}, {C,D,E}, {F,G,H,I}, {J}}

I've racked my brains, but have been unable to think of an elegant
solution, but instead managed the following Fortran-like function:

MyPartition[list1_, list2_] :=
Module[{ans,l},
	ans={};
	l = list1;
	Do	[
		AppendTo[ans, Take[l, list2[[i]]]];
		l = Drop[l, list2[[i]]],
		{i, Length[list2]}
		];
	ans
	]

Someone put me out of my misery!  How can I code this in a more efficient
manner?!

Paul E Howland                                  Tel. +44 (0)1684 895767
Long Range Ground Radar Sensors                 Fax. +44 (0)1684 896315
LSC2 Division                                 Email. PEHOWLAND at DRA.HMG.GB
Defence Research Agency
St Andrews Road
Malvern
Worcestershire, WR14 3PS, UK
=========================================================================



  • Prev by Date: Re: Numerical Solutions to Schrod Eq with Mathematica
  • Next by Date: Re: Equation for Circle in 3-D surrounding Equilateral Triangle
  • Previous by thread: Re: There must be a better way!
  • Next by thread: RE:There must be a better way!