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 prob is less than or equal to zero, the method returns the item with the most recently subtracted probability.

Download the ChooseItemsWithProbabilities example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.37.89