Reputation: 9351
making an android app to do a lottery prize system.
I want to randomly select winners of prizes. but each of the prizes are in different amounts. they are currently stored in a database as three columns, first is index id, auto incremented, the second is the name of the prize, and third is the number of each of these prizes.
for example the most expensive prize is a car and there will be only one of them. but the next cheaper prize will be a small 50 cc scooter, about 10 of them. and the list goes down to to a pencil and pen set where there are 800 winners for this prize.
so the chance of winning the pencil and pen set is much higher than the other prizes.
i am trying to get the idea on what is the best way to code this. i understand that random number generator and even a better one that more evenly distributes true random numbers.
what i am not clear on is the best way to go about this with the different frequency for each of the prizes.
can someone point me in the right direction for this?
Upvotes: 0
Views: 960
Reputation: 38439
Random rand = new Random();
int pickedNumber = rand.nextInt(100);
if(pickednumber>99)
{
pen or pencil
}
else
{
car
}
I'm giving you example and you must me add more condition for scooter or any thing which you want to add on lottery.
Upvotes: 1
Reputation: 28706
Compute the sum of "number of each of these prizes".
Pick a random number between 1 and this sum.
Then order the prizes according some criteria and associate a range to each price (the only car will have the range [1;1]).
Ensure the ranges don't overlap each other. The size of each range must be equal to amount of available prices.
Find the range holding your random number and that's it.
Upvotes: 2
Reputation: 70949
Easiest and least error prone way => put all the prizes in an array. Each prize should be put as many times as there are prizes of the given type. Then generate a random number up to the size of the array and see what is the prize at the given index.
Note that this only considers the case when you know the given user will win a prize. Maybe you should first give a way bigger chance for the user not to win anything for instance say you have 4000 total prizes and you want a user to win a prize with 1/40 chance. So generate a random number up to 40*4000 = 160000
and if the number is not less than 4000
the user wins nothing, otherwise he wins the prize at the index corresponding to the generated value.
Upvotes: 1