471,851 Members | 979 Online

# java giving 50% chance

i know math.random can randomly generate numbers, but i want to know is there a way to let the system decides which variable to choose from a and b?
i want to set both can randomly be selected (50 - 50) chance?
Apr 9 '08 #1
6 15454
r035198x
13,262 8TB
i know math.random can randomly generate numbers, but i want to know is there a way to let the system decides which variable to choose from a and b?
i want to set both can randomly be selected (50 - 50) chance?
Math.random generates numbers between 0.0 and 1.0
Half of that is 0.5.
Ideally then, numbers in [0.0, 0.5) have a 50% chance of getting generated.
Apr 9 '08 #2
Math.random generates numbers between 0.0 and 1.0
Half of that is 0.5.
Ideally then, numbers in [0.0, 0.5) have a 50% chance of getting generated.
yeah...but is there other way then math.random? just curious..
Apr 9 '08 #3
r035198x
13,262 8TB
yeah...but is there other way then math.random? just curious..
java.util.Random ?
Apr 9 '08 #4
1,216 Expert 1GB
java.util.Random?
Indeed. Method Math.random just uses java.util.Random anyway, and the class has a bunch of useful methods. Method Math.random is just leftover from the early API. When you think you need a source of randomness you should check out class Random first.
Apr 9 '08 #5
drsmooth
112 100+
if u use the java.util.Random, you could use

Expand|Select|Wrap|Line Numbers
1. Random r = new Random();
2. int choice = r.nextInt(2);
3. if(choice==0)
4.  //choice 1
5. else
6.  //choice b
thats what i would recommend, the nextInt(2); would generate either a 1 or a 0, at what i would assume is a 50-50 chance.
Apr 11 '08 #6
1,216 Expert 1GB
if u use the java.util.Random, you could use

Expand|Select|Wrap|Line Numbers
1. Random r = new Random();
2. int choice = r.nextInt(2);
3. if(choice==0)
4.  //choice 1
5. else
6.  //choice b
thats what i would recommend, the nextInt(2); would generate either a 1 or a 0, at what i would assume is a 50-50 chance.
And if it's a turn-left/turn-right you'd be wanting, there's a method for that in Random. No need to generate 0/1 and then turn it into true/false:
Expand|Select|Wrap|Line Numbers
1. if (rnd.nextBoolean()) {
2.     ...
3. } else {
4.     ...
5. }
Apr 11 '08 #7