I am trying to get a 50/50 chance of get either 1 or 2 in a random generator.
For example:
Random random = new Random(); int num = random.nextInt(2)+1;
This code will output either a 1 or 2.
Let's say I run it in a loop:
for ( int i = 0; i < 100; i++ ) { int num = random.nextInt(2)+1 ; }
How can I make the generator make an equal number for 1 and 2 in this case?
So I want this loop to generate 50 times of number 1 and 50 times of number 2.
The random number is either in the range [0,0.5) or [0.5,1) . So you should use return Math. random() < 0.5; to have a (theoretical) 50/50 chance.
The solution is simple: double r = random.
One way: fill an ArrayList<Integer>
with fifty 1's and fifty 2's and then call Collection.shuffle(...)
on it.
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