开发者

Constrained Random Number Generation

开发者 https://www.devze.com 2023-04-12 18:30 出处:网络
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.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号