给定这个数组
{"easy"=>85%, "medium"=>10%, "hard"=>3%, "very hard"=>2%}
我必须加上一个数量,并通过得到它的概率来分配可能的结果。
结果示例:
Added 10 "amounts"
Result:
Easy -> 8 amounts
Medium -> 2 amounts
Hard -> 0 amounts
very hard-> 0 amounts
要做到这一点最好的方法是什么,而不需要很多的假设和计算,任何公式?
您可以使用接受对象输入的通用map
函数来完成此操作-
const map = (t, f) =>
Object.fromEntries(Object.entries(t).map(([k,v]) => [k,f(v)]))
const amounts = (t, n) =>
map(t, v => Math.round(n * v)) // <- use `map` here
const input =
{easy:0.85, medium:0.1, hard:0.03, vhard:0.02}
console.log(amounts(input, 10))
{
"easy": 9,
"medium": 1,
"hard": 0,
"vhard": 0
}