Reputation: 13718
Let's say I have an array with the following values:
0.7523262
0.9232192
1.5824928
5.2362123
What is the best way to randomly pick a value from this array so that the higher the value, the more likely it is to be selected? There are common functions to make a weighted selection, but they all use mt_rand(), which wouldn't work for something like this.
For example, a value of 2.4652474 would be twice as likely to be picked as a value of 1.2326237.
Upvotes: 0
Views: 521
Reputation: 3735
Compute a random number between 0
and the sum of the entire array.
Sort the array, so that lower numbers comes first.
Start summing up the array, from the left. When the sum is above the random number, you choose the index you have reached.
If you e.g. have
Array = [1, 1.5, 2, 2.5]
Sum of Array = 7
Random = 4
We check the first index. This is below 4
, so we would add the second number 1 + 1.5 = 2.5
, this is not above 4
so we add another number 2.5 + 2 = 4.5
which is above 4
so we choose the third index.
Upvotes: 1
Reputation: 56710
I don't know if it's the best way, but you can accomplish what you describe by calculating the sum of all entries in the array, multiplying that by a random number between zero and one to get the target, and then calculating a running total for all entries in the array until that total exceeds the target. Return the entry that exceeded the target.
Upvotes: 1