Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Percentage using Random

Tags:

java

random

Today I created a function which generates a random number (0, 1, 2 or 3).
But I want yo have a percetage function.

I would like to apply a percentage to every chance to which the generated numbers fall.
Example: 0 will have 60% chance of being drawn, the number 1 19%, ...

 public void GenerGame(){

        Random r = new Random();
        int game = r.nextInt(max - min +1);

        if (game == 0){
            // do something
        }
        else if (game == 1){
            // do something
        }
        else if (game == 2){
            // do something
        }
        else {
            // do something
        }
 } 

Can I do it by using Random?

like image 547
johnsnow85 Avatar asked Aug 08 '16 20:08

johnsnow85


1 Answers

You can definitely do this by re-thinking your RNG.

If you change the random generation range to 0-99, you can think of this as a range of percentages produced, and hence prescribe various behaviors in those ranges.

public void GenerGame(){

    Random r = new Random();
    int game = r.nextInt(100);

    if (game < 60){ // 60%
        // do something
    }
    else if (game < 79){ // 19%
        // do something
    }
    else if (game < 93){ // 14%
        // do something
    }
    else { // 7%
        // do something
    }
} 

You could change the precision to tenths of a percent by boosting the range to 0-999.

like image 99
Sameer Puri Avatar answered Oct 17 '22 15:10

Sameer Puri