Re:Q: efficient list operation wanted
- To: mathgroup at smc.vnet.net
- Subject: [mg13985] Re:[mg13973] Q: efficient list operation wanted
- From: Lou Talman <me at talmanl.mscd.edu>
- Date: Sat, 12 Sep 1998 16:59:10 -0400
- Sender: owner-wri-mathgroup at wolfram.com
K. Duellmann wrote:
> I am looking for an efficient solution of the following problem:
>
> Given two lists L1 = {1,2,3,4,5,3,7,2,3,9} and L2 = {a, b, c}
>
> I want to replace all numbers 3 in L1 by the elements of L2
> successively, that is the first 3 by a, the second 3 by b and the
> third 3 by c. That is I want to get the following modified L1-list:
> {1,2,a,4,5,b,7,2,c,9}.
>
> Replace[] unfortunately replaces elements with a single element only.
> Is there a chance to avoid hideous Do-Loops?
How about:
In[1]:=
CyclicReplace[L_List, x_, R_List]:=
Block[{n = Length[R], pointer = Length[R]},
L /. (x :> Q[[(pointer = 1 + Mod[pointer, n])]])] In[2]:=
stuff = {1, 3, 2, 4, 5, 3, 6, 3, 7, 8, 9, 3} Out[2]=
{1, 3, 2, 4, 5, 3, 6, 3, 7, 8, 9, 3} In[3]:=
Q = {a, b, c}
Out[3]=
{a, b, c}
In[4]:=
CyclicReplace[stuff, 3 ,Q]
Out[4]=
{1, a, 2, 4, 5, b, 6, c, 7, 8, 9, a}
--Lou Talman