-1
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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    you can try `new Random().nextInt(0) + 10`, the probability of selecting 10 should be 100% – AndreiXwe Nov 18 '20 at 15:14
  • 1
    To aid your research, that would be referred to as a *weighted* random choice. It's unclear what weights you want to use, though. – jonrsharpe Nov 18 '20 at 15:16
  • Is there anyway i could assign the probability to a specific number. I need to assign it to .21. Thank you – Vineel Kondapalli Nov 18 '20 at 15:16
  • what can you change on that code? according to the documentation on https://docs.oracle.com/javase/8/docs/api/java/util/Random.html the nextInt method "All bound possible int values are produced with (approximately) equal probability." – X-Pippes Nov 18 '20 at 15:20
  • 1
    Your current code will produce values between 2 and 11 inclusive. Was that your intention? Anyways, see [Random weighted selection in Java](https://stackoverflow.com/questions/6409652/random-weighted-selection-in-java) for some ideas.. – Idle_Mind Nov 18 '20 at 15:26

2 Answers2

0

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.

Persixty
  • 8,165
  • 2
  • 13
  • 35
0

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;
geneSummons
  • 907
  • 5
  • 15