Re: Binary Vector Manipulation

*To*: mathgroup at smc.vnet.net*Subject*: [mg84103] Re: Binary Vector Manipulation*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Mon, 10 Dec 2007 20:34:41 -0500 (EST)*Organization*: The Open University, Milton Keynes, UK*References*: <fjj183$frv$1@smc.vnet.net>

Tara.Ann.Lorenz at gmail.com wrote: > I am need of assistance programming the following scenario: > > I have two vectors composed of 0's and 1's. Vector "A" has 5% 1's > (and 95% 0's) while Vector "B" has 50% 1's and 50% 0's. > > First, I would like to change Vector B to have a "1" in every place > that Vector A also has a "1" (in other words, I will then have more > than 50% 1's in Vector B once this step is completed). > > Then, I would like to *randomly* return Vector B back to a 50/50 > distribution of 1's and 0's. > > I greatly appreciate any proposed programming methods. The following function should do what you are asking for. In[1]:= myFun[A : {0 | 1 __}, target : {0 | 1 __}] /; Length@A <= Length@B && EvenQ[Length@B] := Module[{B, len, pos}, B = target; len = Length@B; B = ReplacePart[B, Position[A, 1] -> 1]; While[Count[B, 1] - len/2 > 0, pos = RandomInteger[{1, len}]; If[B[[pos]] == 1, B[[pos]] = 0]; ]; B ] Then, we make up some data and check that myFun works correctly. In[2]:= Needs["Combinatorica`"] A = RandomPermutation[Join[Table[1, {5}], Table[0, {95}]]]; B = RandomPermutation[Join[Table[1, {50}], Table[0, {50}]]]; c = myFun[A, B]; c == B Count[#, 1] & /@ {A, B, c} Out[6]= False Out[7]= {5, 50, 50} Regards, -- Jean-Marc