26. Choose items with probabilities

The following surprisingly simple method picks items from an array with given probabilities:

// Return a random value where the values have the indicated // probabilities.// The probabilities must add up to 1.0.public static T PickWithProbability<T>(this T[] values,    double[] probabilities){    // Pick a random probability.    double prob = Rand.NextDouble();    // Find the selected item.    for (int i = 0; i < values.Length; i++)    {        prob -= probabilities[i];        if (prob <= 0) return values[i];    }    throw new Exception("Probabilities do not add up to 1.0");}

The method uses the Rand object's NextDouble method to pick a prob value between 0.0 and 1.0. It then loops through the probabilities, subtracting each from prob. When ...

Get Improving your C# Skills now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.