Skip to content

Instantly share code, notes, and snippets.

@mitchallen
Last active January 13, 2022 14:12
Show Gist options
  • Select an option

  • Save mitchallen/cc6f96e30f7eccf10763fe8bf309eb6e to your computer and use it in GitHub Desktop.

Select an option

Save mitchallen/cc6f96e30f7eccf10763fe8bf309eb6e to your computer and use it in GitHub Desktop.
Selected an item from a weighted choice list
// Author: Mitch Allen
// File: weighted-choice.js
export function weightedChoice(source) {
let rnd = Math.random();
let lower = 0.00;
for (let choice in source) {
let weight = source[choice];
let upper = lower + weight;
if (rnd >= lower && rnd < upper) {
return choice;
}
lower = upper;
}
// Never reached 100% and random
// number is out of bounds
return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment