LAB - 10 months ago 45

Java Question

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`

`getWinner`

`null`

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)

Answer

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.