MathGroup Archive 1995

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

Search the Archive

Re: Challenge!

  • To: mathgroup at
  • Subject: [mg972] Re: Challenge!
  • From: colinr at (Colin Rose)
  • Date: Thu, 4 May 1995 05:24:29 -0400

     Paul E Howland writes:

>    I have two lists of equal length M. I wish to generate a third list
>    also of length M, where the ith element of this list is
>    either the ith element of the first  list,
>    or     the ith element of the second list. (with equal probability)
>    eg.    I have a list       n1 = {a,b,c,d,e,f,g}
>           and another         n2 = {A,B,C,D,E,F,G}
>           a valid answer would be: {a,B,C,d,e,F,G}
>    What is the most compact function that could achieve my goal?

Well, one solution to your problem is:

  MapThread[ If[Random[Integer]==1, #1, #2]&, {n1, n2}]


This solution also appears to be somewhat faster than
the various Table[] alternatives. For instance:

In[1]:=    n1 = Range[1,     10000];
           n2 = Range[10001, 20000];

MapThread[If[Random[Integer]==1, #1, #2]&, {n1, n2}]; // Timing
Out[2]=   {9.26667 Second, Null}

Table[If[Random[Integer]==1, n1[[i]], n2[[i]]], {i, Length[n1]}]; // Timing
Out[3]=   {12.4 Second, Null}

Table[Part[{n1, n2}, 1+Random[Integer], i], {i, Length[n1]}]; // Timing
Out[4]=   {14.9833 Second, Null}

Timings on a Mac Quadra 700.



Colin Rose
tr(I) - Theoretical Research Institute
colinr at

  • Prev by Date: Re: Programming: List Structure Manipulation
  • Next by Date: Re: Galois package for Mathematica
  • Previous by thread: Re: Challenge!
  • Next by thread: Re: Challenge!