Search code examples
javaalgorithmrandomprobability

How to increase propability of a certain number for random() in Java?


First of all, the method I am currently using for picking up a random number within a range of 1-45 is:

public int getRandomNumber(int min, int max) {
    return (int) ((Math.random() * (max - min)) + min);
}

What I want to do is, suppose that there are six numbers in an array of int

int[] numbers = [2, 4, 6, 8, 10, 12];

and I want to increase the probability (about 20% to 30%) for picking that numbers in the array from a randomly generated number in a range of 1 ~ 45.

Is there any way to solve this problem?

Thanks.


Solution

  • Use java.util.Random instead of Math.random. It has nicer functions like random.nextInt().

    And for the increased probability, use the approach suggested by Zabuzard's comment How to increase propability of a certain number for random() in Java?

    static final int[] numbers = new int[]{2, 4, 6, 8, 10, 12};
    
    static final Random random = new Random();
    
    public int getRandomNumber(int min, int max) {
        int p = random.nextInt(10);
        if (p < 3) {
            return numbers[random.nextInt(numbers.length)];
        } else {
            return min + random.nextInt(max - min);
        }
    }
    

    Here, 30% of the time, we pick one of the 6 'special' numbers, and 70% of the time, we pick one of the numbers in the min-max range.

    I'm not sure if that is exactly what you want, but you can tweak the ratio until you find something that matches your needs.