I wanted to write a simple function that allows to roll random item from list, i did it with this code:
this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];
this.assign_resource = function() {
var index = tools.rnd(0, this.resources.length - 1);
return this.resources[index];
};
But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.
Edited -----
for example this could be new list:
this.resources = [
{ type: 'empty', chance: 30 },
{ type: 'nitrogen', chance: 10 },
{ type: 'silicon', chance: 20 },
{ type: 'cobalt', chance: 30 },
{ type: 'magnesium', chance: 10 }
];
How to use it now to make it happen properly?
Edited 2 -----
I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.
This is how I'd implement the solution. Step 1: accumulate all the possible chances Step 2: pick a random value in proportion to total chance Step 3: loop through the resources to see in which part it random value falls under.
I'd solve it by having an array of objects with a chance to be the result, totalling
1.0
, then picking a random number between 0 and 1, and then iterating over the resources and check if adding it to a cumulative total includes your random number.You can do something like this.
Creating an array with the same value multiple times gives it a higher chance of being selected.
Here is another implementation.
I would set it up so that only the actual resources are in your array and "empty" happens if the random roll falls outside of those.