This question already has an answer here:

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.


marked as duplicate by Philipp, DMGregory Aug 23 '18 at 13:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


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
  • 1
    \$\begingroup\$ +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 } \$\endgroup\$ – John McDonald Aug 30 '11 at 14:49
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Ølsted Aug 30 '11 at 16:04
  • \$\begingroup\$ 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. \$\endgroup\$ – Richard Fabian Aug 30 '11 at 16:22
  • \$\begingroup\$ That is not precision but if they deterministic, as they are for the most part. Floating points are always approximations, but not precise. \$\endgroup\$ – 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;

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