Limited random number generation

I need to create 500 numbers, 250 1 s and 250 0, randomly located. Below I do it now. But this is normal when the conclusion is correct.

trialNo=500 RandomSample@Flatten [Table[#, {trialNo/2}] & /@ {0, 1}] 
+6
source share
2 answers

I would do something a little different. Since you are looking for a random permutation Flatten[{ConstantArray[0,250], ConstantArray[1,250]}] , I would generate the permutation and use Part to get the list you are looking for. Properly,

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

It does not work in different ways than what you do, but I think that it mathematically reflects what you are trying to achieve better.

+6
source

Here is another way to do it.

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

Now with a lot of magic for the guys in the chat.

 Mod[ RandomSample@Range @#, 2] & @ 500 
+3
source

Source: https://habr.com/ru/post/899138/


All Articles