Monday, 5 June 2017

Randomly drawing an element from a collection with varied probabilities

Let's say I have a bag with 10 marbles: 5 red, 3 green and 2 blue. I want to randomly draw one marble.

I need to do it in Node.js and considered simple array of objects like:

[
    { color: "red", score: 5},
    { color: "green", score: 3},
    { color: "blue", score: 2}
]

then rolling a number and iterating through the array until score total would be greater than rolled number.

Still, perhaps this simple algorithm could use some refinement (perhaps sorting the array ahead of drawing?), replacing entirely with better one or there is some better data structure?



via Forseti

No comments:

Post a Comment