Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm wondering if anyone can guide me with following problem... Each fruit has different chance to be called out.

Apple - 80% 
Orange - 10%
Banana - 10%

Each time a user click on the random image, only 1 fruit will come out with above weight. I have no idea how I can calcuate to get that result. Pseudo code example is fine for me.

share|improve this question
possible duplicate of Algorithm for determining random events. The accepted answer there is exactly what you need to solve your problem. – bummzack Aug 30 '11 at 13:56
up vote 5 down vote accepted

Randomize a number between 1 and 100, then:

n <= 80: show Apple
n > 80 and n <= 90: show Orange
n > 90 and n <= 100: show Banana
share|improve this answer
+1, but depending on the language, it's easier to just to use the double value between 0.0 and 1.0 that the random method gives you (java, C#, VB...), so: if(n <= 0.8){ show Apple } else if(n <= 0.9){ show Orange } else { show Banana } – John McDonald Aug 30 '11 at 14:49
Remember that floating points isn't precise. 0.3 is actually 2.99, so if you want to be 100% precise you need to user integers. – Peter Ølsted Aug 30 '11 at 16:04
floating points are precise, but you're asking a bit much with 0.3, as it's made up of tenths which are only approximated in floats. If you used 0.25, then that would be perfectly represented. For the question however, such perfection is a non-issue. – Richard Fabian Aug 30 '11 at 16:22
That is not precision but if they deterministic, as they are for the most part. Floating points are always approximations, but not precise. – Peter Ølsted Aug 30 '11 at 18:57
int TotalWeight = 100;
int[] ItemWeights = new int[] {80, 10, 10};
enum Items {Apple, Orange, Banana}

Items GetRandomItem()
    int random = Random.Next(TotalWeight);
    int i=0;  

    while (random > ItemWeights[i])
        random -= ItemWeights[i];

    return (Items) i;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.