Reputation: 505
I want to generate a random number with a given probability but I'm not sure how to:
I have a two dimensional array: int[ ][ ] aryNumbers = new int[4][]
and for each number(4) I want to generate a int result in a inteval of [1...9] with a prob of 0.5 .Otherwise a number in a interval of [10...99].
Note: I know how to generate a number, but choosing between intervals confused me.
Edit:
public int numberAttribution(){
Random rand = new Random();
double dbNum = rand.nextDouble();
int intNum;
int min1 = 1, max1 = 9, range1 = max1 - min1 + 1;
int min2 = 10, max2 = 99, range2 = max2 - min2 + 1;
if(dbNum < 0.5){
intNum = rand.nextInt(range1) + min1;
}else{
intNum = rand.nextInt(range2) + min2;
}
System.out.print(intNum);
return intNum;
}
Upvotes: 1
Views: 357
Reputation: 5103
I assume this method will be called millions of times a second. In that case it might be wise to only generate one random each time:
private static int generateRandom() {
double rand = Math.random();
if (rand < 0.5) {
rand *= 18;
rand += 1;
} else {
rand -= 0.5;
rand *= 180;
rand += 10;
}
return (int) rand;
}
Upvotes: 1
Reputation: 108
So if I got you right, you want a 50% chance to generate a number between 1 and 9, otherwise generate a number between 10 and 99?
In that case you could do it like this:
int randomNumber = 0;
if (Math.random() > 0.5) {
randomNumber = 1 + (int) (Math.random() * 9);
} else {
randomNumber = 10 + (int) (Math.random() * 90);
}
Upvotes: 1