Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a 50/50 chance in random generator

Tags:

java

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.

like image 281
Sulaiman Alyahya Avatar asked Mar 08 '13 02:03

Sulaiman Alyahya


People also ask

How do you get a 50/50 chance in Javascript?

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.

How do you do random chance in Java?

The solution is simple: double r = random.


1 Answers

One way: fill an ArrayList<Integer> with fifty 1's and fifty 2's and then call Collection.shuffle(...) on it.

like image 57
Hovercraft Full Of Eels Avatar answered Oct 23 '22 18:10

Hovercraft Full Of Eels