Re: Challenge!

• To: mathgroup at christensen.cybernetics.net
• Subject: [mg922] Re: Challenge!
• From: Gennady <stupakov at slac.stanford.edu>
• Date: Wed, 3 May 1995 00:01:08 -0400
• Organization: SLAC

```In article <3nkc03\$mq8 at news0.cybernetics.net> Paul E Howland,
PEHOWLAND at taz.dra.hmg.gb writes:
>Dear Mathgroup,
>
>I have two lists of equal length M.
>
>I wish to generate a third list also of length M, where the i th element
>of this list is either the i th element of the first list, or the i th
>element of the second list.
>
>It should be equally probable that the new element be chosen from the
>first or second list.
>
>eg.  I have a list {a,b,c,d,e,f,g}
>     and another   {A,B,C,D,E,F,G}
>
>                   {a,B,C,d,e,F,G}
>                   {a,b,c,d,E,f,g}
>                   {A,B,C,D,e,f,G}
>                   etc.
>
>The function I have written to do this is:
>
>	swap[list1_List, list2_List] :=
>	Module[{newlist={},M},
>               M = Length[list1];
>               Do [AppendTo[
>                            newlist,
>                            If[Random[]>0.5, list1[[i]], list2[[i]]]
>                           ],
>                   {i, M}
>                  ];
>               newlist
>               ]
>
>which works fine, but it really isn't very elegant in terms of
Mathematica's
>functional programming style.  There must be a more compact way to do
this
>in terms of Mapping functions, and so on.
>
>What is the most compact function that could achieve my goal?
>
>Paul.
>
>

Here is a shorter way to do the job:

In[18]:=
l1={a,b,c,d,e,f,g};
l2={A,B,C,D,E,F,G};

In[47]:=
swap[l1_,l2_]:=Map[Part[#,Random[Integer,{1,2}]]&,
Transpose[{l1,l2}]]//Flatten

In[48]:=
swap[l1,l2]

Out[48]=
{A, b, C, d, E, F, g}

In[49]:=
swap[l1,l2]

Out[49]=
{a, b, C, d, e, f, G}

Regards,

```

• Prev by Date: Help me derive this function
• Next by Date: Re: How use the Union function (MMA v.2,2 on PC )?
• Previous by thread: Re: Challenge!
• Next by thread: Re: Challenge!