1

Now , I will generate random numbers between 1 to 5. I assume there has probability or chance to gain on each number . (please assume for example if you don't agree it)

1 has 20%

2 has 20%

3 has 20%

4 has 20%

5 has 20%

I would like to increase or decrease chances of some numbers as I wish..

1 has 10%

2 has 10%

3 has 35%

4 has 40%

5 has 5%

If so , I can generate random numbers as I wish. Some were hard to get and some will gain frequently. How can I achieve it by Java ? Please support me with some examples or some useful links or anything else. I would really appreciated it. Please don't be suggest to describe some my efforted codes because I have no idea for this and I request some useful suggestions from you . Thanks in advance.

Community
  • 1
  • 1
Cataclysm
  • 7,592
  • 21
  • 74
  • 123
  • 5
    You've got percentages - so imagine you rolled a die with a value from 1-100. 1-10 => 1. 11-20 => 2. 31-55 => 3. 56-95 => 4. 96-100 => 5. Now think about how to code that. – Jon Skeet Mar 18 '14 at 08:32
  • 1
    Create a list with 10 ones, 10 twos, 35 threes, 40 fours and 5 fives. Shuffle the list. Pick the first element. Voilà! – Matt Mar 18 '14 at 08:32
  • @AskThakare as my described , `Some were hard to get and some will gain frequently.` – Cataclysm Mar 18 '14 at 08:36

4 Answers4

15

The solution is simple:

double r = random.nextDouble();
if (r < 0.1) ret = 1
else if (r < 0.2) ret = 2
else if (r < 0.55) ret = 3
...

you get the idea, use the cumulative likelihood as threshold.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
4

First instantiate java.util.Random rand = new java.util.Random();. Do this exactly once.

From there, one approach is to use double f = rand.nextDouble(); which gives you a number between (and including) 0 to (and not including) 1.

Then transform using a series of ifs:

if (f < 0.1){
    return 1;
} else if (f < 0.1 + 0.1){
    return 2;
} else if (f < 0.1 + 0.1 + 0.35){
    return 3;
... /*can you see the pattern*/

It's not quite the fastest way, but is clear and will get you started.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

I don't know if there is a way with the Random library. But I think you can generate a Random number between 1 and 100. And so, you can code that between:

1 and 10 you obtain 1, 11 and 20 you obtain 2, 21 and 55 you obtain 3,

and so on

Karura91
  • 603
  • 6
  • 15
0

An alternative I can think about it is

int[] a = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 
4, 4, 4, 4, 4, 5, 5, 5, 5, 5};

Random r = new Random();
return a[ r.nextInt(100) ];
Tun Zarni Kyaw
  • 2,099
  • 2
  • 21
  • 27