嗨,
我有这个函数可以根据概率生成随机结果:
function odds(pairs) {
const n = Math.random() * 100;
const match = pairs.find(({value, probability}) => n <= probability);
return match ? match.value : last(pairs).value;
}
function last(array) {
return array[array.length - 1];
}
const result = odds([
{value: 'hit', probability: 1},
{value: 'miss', probability: 2}
]);
这适用于正数但不适用于负数,如下例所示:
const result = odds([
{value: 'hit', probability: -1},
{value: 'miss', probability: -2}
]);
这总是会导致错过。我怎样才能让它也适用于负数?
谢谢。
简单:
function odds(pairs) {
const n = Math.random() * (pairs[0].probability + pairs[1].probability);
const match = pairs.find(({value, probability}) => (n <= probability));
return match ? match.value : last(pairs).value;
}
function last(array) {
return array[array.length - 1];
}
const result = odds([
{value: 'hit', probability: -2},
{value: 'miss', probability: -1}
]);
此代码适用于正数或负数!
我做了什么:
因为命中概率 + 未命中概率 = 100%(没有第三种可能性),只需将
Math.random
乘以它们的总和,而不是乘以 100。这样,结果将取决于它们的比率,而不是第一个值 / 100。