Search code examples
javarandomapache-commons

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?


Solution

  • 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.