Re: Challenge!
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg917] Re: Challenge!
- From: Lou D'Andria <lou>
- Date: Sun, 30 Apr 1995 03:51:40 -0400
- Organization: Wolfram Research, Inc.
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} > >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. [...] >What is the most compact function that could achieve my goal? Well, using Listable Plus[] and Times[], how about something like swap2[list1_List,list2_List] := list1 + (list2 - list1) Table[Random[Integer],{Length[list1]}] The use of Length[list1] can also be removed, to make it a bit more compact. swap3[list1_List, list2_List] := list1 + (list2-list1) (Random[Integer]& /@ list1) One drawback to this method is that if you wanted to choose elements from 3 or more lists, the formulas underlying the method become increasingly complex, unlike the solution posted previously swap4[list1_List, list2_List] := #[[1+Random[Integer]]]& /@ Transpose[{list1,list2}] which is easily generalized to more than two lists. swap4a[lists__] := With[{len = Length[First @ {lists}]}, #[[ Random[Integer,{1,len}] ]]& /@ Transpose[{lists}] ] Lou