Re: repeating elements in a list
- To: mathgroup at smc.vnet.net
- Subject: [mg54978] Re: [mg54878] repeating elements in a list
- From: János <janos.lobb at yale.edu>
- Date: Tue, 8 Mar 2005 05:04:37 -0500 (EST)
- References: <200503050634.BAA00963@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
On Mar 5, 2005, at 1:34 AM, Torsten Coym wrote: > Hello, > suppose I have list > lst={A, B, C} > and I want to create a new list, where all elements are repeated n > times > so that (for n=3): > newlst={A, A, A, B, B, B, C, C, C} > I have the following code to do this: > n=3; > newlst=Flatten[Table[Table[lst[[i]], {n}], {i, Length[lst]}]]; > but I'm pretty sure, that there must be a more elegant way to solve the > problem. > thank you I was thinking to generalize a less efficient solution like: In[197]:= Flatten[Cases[Tuples[lst, n], {x1_, x2_, x3_} /; x1 == x2 == x3]] Out[197]= {a, a, a, b, b, b, c, c, c} If I construct the pattern {x1_,x2_,x3_ } this way: In[254]:= Table[ToExpression[ StringJoin["x", ToString[ i], "_"]], {i, 1, n}] Out[254]= {x1_, x2_, x3_} then it still works and gives: In[249]:= Cases[Tuples[lst, n], Table[ToExpression[ StringJoin["x", ToString[i], "_"]], {i, 1, n}] /; x1 == x2 == x3] Out[249]= {{a, a, a}, {b, b, b}, {c, c, c}} If I construct the condition this way: In[263]:= Flatten[Fold[Equal, First[Table[ToExpression[ StringJoin["x", ToString[i]]], {i, 1, n}]], Rest[Table[ToExpression[ StringJoin["x", ToString[i]]], {i, 1, n}]]]] Out[263]= x1 == x2 == x3 and insert into the Case statement, then it does not work. Any good explanation for it ? What is the right way to build up a condition programatically ? Thanks ahead, János
- References:
- repeating elements in a list
- From: Torsten Coym <torsten.coym@eas.iis.fraunhofer.de>
- repeating elements in a list