Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: repeating elements in a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg54993] Re: repeating elements in a list
  • From: Peter Pein <petsie at arcor.de>
  • Date: Wed, 9 Mar 2005 06:34:19 -0500 (EST)
  • References: <200503050634.BAA00963@smc.vnet.net> <d0juuh$n6f$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

János wrote:
> 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
> 
> 
> 
> 
Condition[] (/;) has atrribute HoldAll set. If you really insist on
constructing an expression which is logically equivalent to
Equal@@x/@Range[n] in this manner, write Evaluate[Flatten[....]].

b.t.w. Why don't you use the property of {x1,x2,..,xn} when constructing
the pattern?

In[1]:= n=3; lst={a,b,c};
In[3]:= Cases[Tuples[lst,n],Table[x_,{n}]]//Flatten
Out[4]= {a,a,a,b,b,b,c,c,c}

-- 
Peter Pein
Berlin


  • Prev by Date: Re: BS PDE
  • Next by Date: Re: help with mathematica
  • Previous by thread: Re: repeating elements in a list
  • Next by thread: Re: repeating elements in a list