# How do I pick a random number within a range, but weighted relative to one part of that range? (in Java)

I want to select random numbers in a range of numbers, but heavier than a portion of that range. For example:

• Pick a random number between 1-10
• Weight so that 1-5 can be 20% more than 6-10

Is it possible? How should I do it?

+3

source to share

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

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 at 1-5 60% of the time and a number at 6-10 40% of the time.

+11

source

Roll and add multiple cubes to form a bell-shaped probability curve. Then subtract the average. Repeat roll if negative. The more cubes roll, the more it weighs.

Here's one path, completely 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 the dice on any number of sides to get the range you want. You control the frequency curve by choosing the number of bones.

+1

source

Two solutions come to mind. First, do an arbitrary case 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 can fill the array with digits by adding more numbers you want more and pick a random value along the length of the array.

0

source

Try the following:

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

```
0

source

All Articles