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}]
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With