Don Rhummy
Don Rhummy

Reputation: 25830

How choose random number within range, but weighted toward one part of that range? (in Java)

I want to choose random numbers within a range of numbers, but with weighting towards part of that range. For example:

  1. Choose random number between 1-10
  2. Weight it so that 1-5 is maybe 20% more likely than 6-10

Is this possible? How would I do this?

Upvotes: 4

Views: 4738

Answers (4)

Adam Liss
Adam Liss

Reputation: 48290

Try this:

public int weightedRandom() {
  int rand = Math.floor(Math.random() * 5 + 1) // From 1 to 5
  if (Math.random() >= 0.6) {
    ++rand;
  }
  return rand;
}

Upvotes: 0

Tony Ennis
Tony Ennis

Reputation: 12299

To generate a bell curve of probabilities, roll and sum multiple dice. Then subtract the average. Re-roll if the result is negative. The more dice rolled, the more weighting.

Here's one way, wholly untested.

float sum;
do {
   sum = rollThreeDice(); // returns 3 to 18, with an average is 10.5
   sum -= 10.5;           // Now the range is 0 to 7.5, with the lower end being more likely.
   } while(sum < 0);
return sum;

Of course you can roll dice with any number of sides in order to produce the desired range. You control the frequency curve by choosing the number of dice.

Upvotes: 1

GavinCattell
GavinCattell

Reputation: 3963

Two solutions come to mind. First, run a random twice:

java.utils.Random randomGenerator = new java.utils.Random();
int random = randomGenerator.nextInt(11);
if(random <= 6) { //This is 20% more
    random = randomGenerator.nextInt(5) + 1;
} else {
    random = randomGenerator.nextInt(5) + 6;
}

Or if you always have a static range, you could fill an array with the numbers, adding more of the numbers you want more of and choose a random over the length of the array.

Upvotes: 0

trutheality
trutheality

Reputation: 23465

It depends on how you want your probability distribution to look like.

For example:

Pick a random number between 1-10
If it is <= 6
    Return a random number between 1-5
Else
    Return a random number between 6-10
EndIf

Picks a number in 1-5 60% of the time and a number in 6-10 40% of the time.

Upvotes: 11

Related Questions