I want to create a weighted random number generator in CoffeeScript.
Here is the Javascript code:
// 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];
Of course I can create it in a not very elegant way (without the variable init):
for chance, value of chances
for [1..value]
bag.push(chance)
index = Math.floor(Math.random()*bag.length;
element = bag[index];
I want to simplify the code, and create the best solution but I’m stucked:
bag = ((k for [1..v]) for k, v of chances)
This code create an Array with Arrays in it with the desired values, but not that I want obviously, and I don’t know how to do it in a nice way.
I think what you are looking for is something like:
However, personally I do not think this path leads to simpler code at all (as you wrote you were trying to reach). Your first take with two for loops is simple and directly understandable by all programmers. I would stick with that.
Also note that if you look at the Javascript code generated by these solutions the double for loop is a lot less complex.