jeudi 19 mai 2016

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());
    Arrays.sort(copy);

    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 random is > 90, getWinner returns null. 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.




Aucun commentaire:

Enregistrer un commentaire