MathGroup Archive 1995

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

Search the Archive

Re: Challenge!

  • To: mathgroup at christensen.cybernetics.net
  • Subject: [mg962] Re: [mg889] Challenge!
  • From: Richard Mercer <richard at seuss.math.wright.edu>
  • Date: Thu, 4 May 1995 03:44:15 -0400

Paul,

Here's a one-liner that works with any number of such lists.
It does not require knowing the number of lists or their length 

in advance, though it does require they be of the same length.

(* setup *)
lst1 = {a,b,c,d,e,f,g};
lst2 = {A,B,C,D,E,F,G};
lists = {lst1,lst2};

(* routine *)
Part[#,Random[Integer,{1,Length[lists]}]]& /@ Transpose[lists]


Richard Mercer

>  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}
>  

>  valid answers would be:
>  		   {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.



  • Prev by Date: DAE Solver in Mathematica?
  • Next by Date: Set Theory on Mathematica
  • Previous by thread: Re: Challenge!
  • Next by thread: Re: Challenge!