Random rng = new Random();
int cardValue = rng.nextInt(10) + 2;
How do I assign a higher probability to draw the number 10 from this code in Java?
Random rng = new Random();
int cardValue = rng.nextInt(10) + 2;
How do I assign a higher probability to draw the number 10 from this code in Java?
Lots of ways!
Random.nextInt(10)
returns a value in the inclusive range [0,9].
So Random.nextInt(10)+2
is [2,11].
One absolutely arbitrary way is:
Random rng = new Random();
int cardValue = rng.nextInt(11) + 2;
if(cardValue==12){
cardValue=10;
}
That will give 10 a probability of 1/5 twice any other value.
If you only want to favour on value, you can 'map' more values to 10.
Another (fast) way is to build up an array with duplicate values that give you the probabilities you want. That's the computation equivalent of drawing from a shuffled deck where (in this case) 10 is on more cards than other numbers. That's with replacement!
If you went further and wanted to simulate drawing without replacement you would by copying the last element to the picked element and reducing the range on each draw.
PS: That may be specimen code but I wouldn't allocate a new Random
on each call.
It provides (if anything) less guarantee about distribution.
You will (in unit testing at least) want to force a seed to make the sequence reproducible - even if you intended it to be different every time in the application.
This may not meet all of your constraints, but it should get you heading in the right direction...
int percent = Random.nextInt(100);
if (percent < 21) {
percent = 10;// 21% of the time
}
else {
percent = percent % 10;// the rest of the time
}
return percent;