1
\$\begingroup\$

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.

\$\endgroup\$
0

2 Answers 2

6
\$\begingroup\$

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
\$\endgroup\$
4
  • 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\$ Commented Aug 30, 2011 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\$ Commented Aug 30, 2011 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\$ Commented Aug 30, 2011 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\$ Commented Aug 30, 2011 at 18:57
4
\$\begingroup\$
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;
 } 
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .