我想在 CoffeeScript 中创建一个加权随机数生成器。
这是Javascript代码:
// init
var chances = {
red: 1,
blue: 4,
yellow: 10
},
bag = [];
// fill the bag with the values
for (var chance in chances) {
for (var i=0; i<chances[chance]; ++i) {
bag.push(chance);
}
}
// get random element
var index = Math.floor(Math.random()*bag.length,
element = bag[index];
当然,我可以用一种不太优雅的方式创建它(没有变量 init):
for chance, value of chances
for [1..value]
bag.push(chance)
index = Math.floor(Math.random()*bag.length;
element = bag[index];
我想简化代码,并创建最好的解决方案,但我被困住了:
bag = ((k for [1..v]) for k, v of chances)
这段代码创建了一个数组,其中包含所需的值,但显然不是我想要的,我不知道如何以一种好的方式做到这一点。