Probability and Random number generator

I'm working on a problem that involves probability and random number generator that I believe I am close with but need help hammering out one last thing. I have a marble bag in which I will enter the number of marbles that are of different color. Meaning Red 10 green 5 blue 5 orange 3. I have to infer the probability of each colored marble, then randomly generate number of marbles based on that probability. So Far I can calculate the probability as so

  int MarbleCnt = red + green + blue + orange;
  double probRed = (double)red / MarbleCnt;
  double probGreen = (double)green / MarbleCnt;
  double probBlue = (double)blue / MarbleCnt;
  double probOrange = (double)orange / MarbleCnt;

then I plan to use the Random().NextDouble to be used to decipher out which marble was picked this is my code:

for (int i = 0; i < 10; i++) {
    double randNum = mRandom.NextDouble();             
    if (0 <= randNum && randNum < probRed) { probArr[i] = RED_MARBLE; }
    else if (probRed <= randNum && randNum < probGreen) { probArr[i] = GREEN_MARBLE; }
    else if (probGreen <= randNum && randNum < probBlue) { probArr[i] = BLUE_MARBLE; }
    else  { probArr[i] = ORANGE_MARBLE; }
}

My issue is what do I do if I have the same number of marbles, Meaning I have 10 red and 5 blue and 5 orange what do I need to do to decipher to pick a blue or an orange.

Jon Skeet
people
quotationmark

Personally, I wouldn't use double at all - I'd just pick a random integer between 0 (inclusive) and the total number of marbles (exclusive). Effectively, you'd be "labelling" each marble with a number, and then working out which marble was picked based on the random integer. For example:

MarbleColor PickMarble
    (Random rng, int redCount, int greenCount, int blueCount, int orangeCount)
{
    int index = rng.Next(redCount + greenCount + blueCount + orangeCount);
    if (index < redCount)
    {
        return MarbleColor.Red;
    }
    if (index < redCount + greenCount)
    {
        return MarbleColor.Green;
    }
    if (index < redCount + greenCount + blueCount)
    {
        return MarbleColor.Blue;
    }
    return MarbleColor.Orange;
}

This is basically the same approach as you've got with doubles, but simpler (IMO) to understand.

people

See more on this question at Stackoverflow