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: [mg2348] RE:There must be a better way!
  • From: jpk at apex.mpe.FTA-Berlin.de (Jens-Peer Kuska)
  • Date: Fri, 27 Oct 1995 01:48:17 -0400

> From  Tue Oct 24 11:54:33 1995
> From: pehowland at taz.dra.hmg.gb ()
To: mathgroup at smc.vnet.net
> To: mathgroup at smc.vnet.net
> Subject: [mg2322] There must be a better way!
> Organization: LSC2 Division, Defence Research Agency
> Content-Length: 1040
> X-Lines: 37
> 
> 
> 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
> =========================================================================
> 
> 

Your definition is recursive, the recursion is done by
mpartAux. MultiPartition is the top level and checks if the
recusion can terminate. Try:


mpartAux[lst_List,{}]:=lst   
mpartAux[lst1_List,ilst:{__Integer}]:=
  Prepend[
    mpartAux[
      Drop[lst1,First[ilst]],
      Rest[ilst]
     ],
    Take[lst1,First[ilst]]]

 MultiPartition[lst1_List,ilst:{__Integer}]:=
   mpartAux[lst1,ilst] /; Length[lst1]==(Plus @@ ilst)   
   
The Example

l1={a,b,c,d,e,f,g,h,j}
l2={2,2,2,3}


MultiPartition[l1,l2]


{{a, b}, {c, d}, {e, f}, {g, h, j}}

I hope that helps
Jens



  • Prev by Date: Re: Equation for Circle in 3-D surrounding Equilateral Triangle
  • Next by Date: Erase postscript cells
  • Previous by thread: Re: There must be a better way!
  • Next by thread: Questions on data transferring and analysis