Search code examples
javarandomlibgdxprobabilityprobability-theory

Random Number Generator Biased To Numbers in the Middle of Range, Java, libGDX


I am designing a game in libGDX which drops different sized rocks for the user to dodge.

My Question: How can I create a method which takes in a low and high int value, and returns a random number. However, I want this random number to be biased toward the middle of the range (similar to a normal distribution).

I would like the method to look something like this: public int randBiasInt(int low, int high) { }


Solution

  • Something to the sort of this should work...

    public int getBiasedInt(int min, int max) {
        int rand = Math.random() * max;
        while (rand < min) {
            rand = Math.random();
        }
        int mid = (max / 2) - (min / 2);
        int halfmid = mid / 2;
        if (rand > mid) {
            rand -= Math.random() * halfmid;
        } else {
            rand += Math.random() * halfmid;
        }
        return rand;
    }
    

    Not the prettiest, I know. But it should be acceptable for what you desire...