Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrained Random Number Generation

I need to generate 500 numbers, 250 1s and 250 0s, randomly located. Below is what I do now. But it does not feel right while the output is correct.

trialNo=500

RandomSample@Flatten[Table[#, {trialNo/2}] & /@ {0, 1}]
like image 663
500 Avatar asked Oct 12 '11 15:10

500


2 Answers

I'd actually do something slightly different. Since you're looking for a random permutation of Flatten[{ConstantArray[0,250], ConstantArray[1,250]}], I'd generate the permutation and use Part to get the list you're looking for. As follows,

perm = RandomSample[Range[trialNo]];
Flatten[{ConstantArray[0, trialNo/2], ConstantArray[1, trialNo/2]}][[ perm ]]

This isn't operationally different than what you're doing, but I think it captures mathematically what your trying to accomplish better.

like image 98
rcollyer Avatar answered Sep 21 '22 10:09

rcollyer


Here is another way to do this.

Round[Ordering[1~RandomReal~#] / N@#]& @ 500

Now with more magic for the guys in Chat.

Mod[RandomSample@Range@#, 2] & @ 500
like image 36
Mr.Wizard Avatar answered Sep 22 '22 10:09

Mr.Wizard