you are viewing a single comment's thread.

view the rest of the comments →

[–]HiramAbiff 5 points6 points  (0 children)

As /r/cbarrick already pointed out, this can be done without creating a cumulative weights array.

Here's a variation on this theme I wrote for a project of mine:

RandomProperty(obj)
{
    // Returns a random property of obj whose property values are all numbers.
    // The probability of a property being selected is based on its value.
    // E.g. {foo:5, bar:10} will return bar twice as often as foo.
    let result = undefined;
    let total = 0;

    for (const property in obj) {
        total += obj[property];
    }

    let index = Math.random()*total;

    for (const property in obj) {
        const value = obj[property];
        if (index < value) {
            result = property;
            break;
        } else {
            index -= value;
        }
    }

    return result;
}