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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.