selection based on percentage weighting

Viewed 25443

I have a set of values, and an associated percentage for each:

a: 70% chance
b: 20% chance
c: 10% chance

I want to select a value (a, b, c) based on the percentage chance given.

how do I approach this?


my attempt so far looks like this:

r = random.random()
if r <= .7:
    return a
elif r <= .9:
    return b
else: 
    return c

I'm stuck coming up with an algorithm to handle this. How should I approach this so it can handle larger sets of values without just chaining together if-else flows.


(any explanation or answers in pseudo-code are fine. a python or C# implementation would be especially helpful)

13 Answers

Based loosely on python's numpy.random.choice(a=items, p=probs), which takes an array and a probability array of the same size.

    public T RandomChoice<T>(IEnumerable<T> a, IEnumerable<double> p)
    {
        IEnumerator<T> ae = a.GetEnumerator();
        Random random = new Random();
        double target = random.NextDouble();
        double accumulator = 0;
        foreach (var prob in p)
        {
            ae.MoveNext();
            accumulator += prob;
            if (accumulator > target)
            {
                break;
            }
        }
        return ae.Current;
    }

The probability array p must sum to (approx.) 1. This is to keep it consistent with the numpy interface (and mathematics), but you could easily change that if you wanted.

Related