问题
Numpy.random.choice is a nice simple function, that lets you sample an array of ints based on some probability distribution:
>>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
array([3, 3, 0])
Is there an equivalent in javascript (node js)?
Note: I found this package https://www.npmjs.com/package/random-weighted-choice but I don't like creating a hashmap/table every time I need to get a sample.
回答1:
You could use this ES6 code:
function randomChoice(p) {
let rnd = p.reduce( (a, b) => a + b ) * Math.random();
return p.findIndex( a => (rnd -= a) < 0 );
}
function randomChoices(p, count) {
return Array.from(Array(count), randomChoice.bind(null, p));
}
let result = randomChoices([0.1, 0, 0.3, 0.6, 0], 3);
console.log(result);
The reduce part calculates the sum of the probabilities. If it is expected that these always amount to 1, then of course that call is not necessary, and rnd = Math.random() would be enough.
回答2:
You could use lodash's _.sample function:
_.sample([1, 2, 3, 4]);
// => 2
来源:https://stackoverflow.com/questions/41654006/numpy-random-choice-in-javascript