寻找更优雅的方法来解决这个简单的逻辑任务
Looking for more elegant way to solve this simple logic task
这是我试图在练习中解决的一个更大问题的一部分。它看起来像这样:
x 出现的可能性是 y.
的 10 倍
z 出现的频率比 y.
少 2 倍
我通过这样计算一个单位解决了这个问题:
const x = 100;
const y = 10;
const z = 5;
const unit = 100 / (x + y + z);
单位等于0.87
所以当我做 (0.87) + (0.87 * 10) + (0.87 * 5) 我得到 100%(几乎)
然后我生成一个介于 0 和 1 之间的随机数。
const randomNumber = Math.random();
function getValue() {
if (randomNumber <= 0.87) {
console.log('x');
} else if (randomNumber > 0.87 && randomNumber < 95.7) {
console.log('y');
} else console.log('z');
}
getValue();
If value<0.87 then I log out x, if value < 0.87+(0.087*10) I log y etc
谁能推荐比这更合乎逻辑、更优雅的方式?
除了 randomNumber > 0.87
多余之外,我觉得你的方式很干净。
如果将值 x
、y
和 z
存储在数组中,您可能可以编写一些更简洁的代码,例如:
let prob = [100, 10, 5];
let sum = prob.reduce((a, b) => a + b, 0);
let normalizedProb = prob.map(p => p / sum);
let cummulativeProb = normalizedProb.map((cummulative => p => cummulative += p)(0));
for (let i = 0; i <= 50; i++) {
let r = Math.random();
console.log(cummulativeProb.filter(p => r >= p).length);
}
此外,您可能需要阅读 this post 以加快实施速度(尽管在 python 中)。不过代码肯定会比较复杂
由于权重是小整数,你可以将x
、y
和z
复制到一个数组中,然后随机选择数组中的一个单元格:
let choices = "zyyxxxxxxxxxxxxxxxxxxxx";
console.log(choices[Math.floor(Math.random() * 23)]);
这里神奇的数字23是选择的数量,1+2+20; Math.floor(Math.random() * 23)
是一个在 [0, 22] 范围内均匀随机的随机整数(包括两个边界)。另见:
- Generating random whole numbers in JavaScript in a specific range?
这是我试图在练习中解决的一个更大问题的一部分。它看起来像这样:
x 出现的可能性是 y.
的 10 倍z 出现的频率比 y.
少 2 倍
我通过这样计算一个单位解决了这个问题:
const x = 100;
const y = 10;
const z = 5;
const unit = 100 / (x + y + z);
单位等于0.87 所以当我做 (0.87) + (0.87 * 10) + (0.87 * 5) 我得到 100%(几乎)
然后我生成一个介于 0 和 1 之间的随机数。
const randomNumber = Math.random();
function getValue() {
if (randomNumber <= 0.87) {
console.log('x');
} else if (randomNumber > 0.87 && randomNumber < 95.7) {
console.log('y');
} else console.log('z');
}
getValue();
If value<0.87 then I log out x, if value < 0.87+(0.087*10) I log y etc
谁能推荐比这更合乎逻辑、更优雅的方式?
除了 randomNumber > 0.87
多余之外,我觉得你的方式很干净。
如果将值 x
、y
和 z
存储在数组中,您可能可以编写一些更简洁的代码,例如:
let prob = [100, 10, 5];
let sum = prob.reduce((a, b) => a + b, 0);
let normalizedProb = prob.map(p => p / sum);
let cummulativeProb = normalizedProb.map((cummulative => p => cummulative += p)(0));
for (let i = 0; i <= 50; i++) {
let r = Math.random();
console.log(cummulativeProb.filter(p => r >= p).length);
}
此外,您可能需要阅读 this post 以加快实施速度(尽管在 python 中)。不过代码肯定会比较复杂
由于权重是小整数,你可以将x
、y
和z
复制到一个数组中,然后随机选择数组中的一个单元格:
let choices = "zyyxxxxxxxxxxxxxxxxxxxx";
console.log(choices[Math.floor(Math.random() * 23)]);
Math.floor(Math.random() * 23)
是一个在 [0, 22] 范围内均匀随机的随机整数(包括两个边界)。另见:
- Generating random whole numbers in JavaScript in a specific range?