johnsnow85
johnsnow85

Reputation: 125

Percentage using 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?

Upvotes: 8

Views: 20520

Answers (1)

Sameer Puri
Sameer Puri

Reputation: 1025

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.

Upvotes: 28

Related Questions