Skip to content

Instantly share code, notes, and snippets.

@danielrw7
Last active December 9, 2015 19:20
Show Gist options
  • Save danielrw7/3f8a2a4f611ad92f948f to your computer and use it in GitHub Desktop.
Save danielrw7/3f8a2a4f611ad92f948f to your computer and use it in GitHub Desktop.
Randomly pick an array element with weighted chances
function pickWeighted(array) {
var n = Math.random(),
totalChances = 0,
total = 0,
result;
array = array.map(function(row) {
var min, max;
var chance = typeof row == 'object' || typeof row == 'function' ? row.chance : 1;
if (chance) {
min = totalChances;
max = totalChances + chance;
totalChances += chance;
} else {
min = max = -1;
}
return {
min: min,
max: max,
value: typeof row == 'object' || typeof row == 'function' ? row.value : row
};
});
for(var c in array) {
var row = array[c];
if ((row.min / totalChances) <= n && (row.max / totalChances) > n) {
return row.value;
break;
}
}
}
/* Basic Usage: */
pickWeighted([1,2,3])
// => 2
pickWeighted([1,2,3])
// => 3
pickWeighted([1,2,3])
// => 2
pickWeighted([1,2,3])
// => 1
/* Weighted Usage: */
pickWeighted([
{chance: 0.1, value: 1},
{chance: 0.5, value: 2},
{chance: 0.4, value: 3},
]);
// => 2
pickWeighted([
{chance: 0.1, value: 1},
{chance: 0.5, value: 2},
{chance: 0.4, value: 3},
]);
// => 3
pickWeighted([
{chance: 0.1, value: 1},
{chance: 0.5, value: 2},
{chance: 0.4, value: 3},
]);
// => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment