Reputation: 43
I want to make a method in java where I can input the maximum and minimum numbers and it will give me a random number, but with a higher chance of a bigger number than a smaller one. How would I do this?
Upvotes: 0
Views: 1374
Reputation: 533492
There is lots of ways to do this depending on what you mean by higher. You can skew your distribution with a function.
int num = (int) (func(Math.random()) * (max - min)) + min;
Your func
could be Math.sqrt
or Math.pow(x, n)
where n < 1
to favour higher numbers.
I would like it to be 10% more likely to have an answer over ten.
If this is your requirement, you actually have two distributions.
private static final Random rand = new Random();
public static int randBetween(int min, int max) {
return rand.nextInt(max - min + 1) + min;
}
int next = rand.nextInt(100) < 10 ? // a 10% chance
randBetween(10, max) : // random of at least 10
randBetween(min, max); // otherwise any number.
Upvotes: 1