How to get the result of random item with different possibility? [duplicate]

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

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, 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];
i++;
}

return (Items) i;
}