LAB LAB - 2 years ago 145
Java Question

Random numbers and percentages in Java

I have some Java code. In my code, I have a collection of users. Each user has a percentage chance of "winning" the collection, as that the sum of the chance of each user in the collection is 100. To choose a winner, I sort the collection (which is an array) in ascending order. My problem is choosing the winner based off of that sorted array. This is what I have tried:

public Bet getWinner() {
double random = Math.random() * 100;

Bet[] copy = Arrays.copyOf(getBets(), bets.size());

for (Bet bet : copy) {
if (random < getChance(bet)) {
return bet;
return null;

public float getChance(Bet bet) {
return (bet.getAmount() / getJackpotTotal()) * 100;

public float getJackpotTotal() {
float total = 0;

for (Bet bet : getBets()) {
total += bet.getAmount();
return total;

But is there are two users in the collection, one with 10% chance of winning and the other with 90%, if
is > 90,
. How else can I do this? Is there a way to create a random distribution based off of a percentage, or is there something simpler or different?

Thanks for your help.


This is not a duplicate because it is not asking specifically about weighted random numbers. It is asking about choosing something (not a random number) from a random number.

Answer Source

Add a variable that keeps a total of the odds you've gone through so far:

int total = 0;
for (Bet bet : copy) {

    if (random < total + getChance(bet)) {
        return bet;
    total += getChance(bet);

Your naming conventions are a little ambiguous, so I hope you get the idea even if I may be a bit inaccurate with the proper names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download