Mazzy
Mazzy

Reputation: 14179

Getting the maximum of a random ranged selection

This is my array

[0.12, 0.13, 0.3, 0.5, 0.75];

From this array I calculate the sum cumulative array:

[ 0.12, 0.25, 0.55, 1.05, 1.8 ]

I generate rand value between the min and max value from the array:

var randNumber = (Math.random() * (max - min)) + min;

in the following case the min=0.12 and the max=1.18

I need to get the interval of the cumulative array in which the rand number falls in. For example the rand number could be 1.5948337644897403 then the number falls between 1.05 and 1.8 then I will pick the 1.05

the issue is that the last element of the array is never picked out. How get the last element of the array?

Upvotes: 1

Views: 34

Answers (1)

Guffa
Guffa

Reputation: 700252

The problem is that you are getting a random value between min and max, and also that you are getting the value lower than the random value. The item that is excluded is actually the first item, but because you get the wrong item all the weights will be wrong, and you will never get the last item.

You should get a random value between zero and max, otherwise you will exclude the first item in the array:

var randNumber = Math.random() * max;

You should then get the item with a value that is higher than the random number:

var index = arr.length - 1;
while (index > 0 && arr[index - 1] >= randNumber) index--;

Here is a test that shows that the weights are correct: http://jsfiddle.net/Guffa/kgbL4rsc/

Upvotes: 2

Related Questions