Skip to content

Instantly share code, notes, and snippets.

@imbcmdth
Created December 14, 2014 18:10
Show Gist options
  • Save imbcmdth/230234e9593e99886faf to your computer and use it in GitHub Desktop.
Save imbcmdth/230234e9593e99886faf to your computer and use it in GitHub Desktop.
Weighted Sampling
function rand (max) { return Math.random() * max; }
function randomSample (array) {
var answer = array[0];
var totalWeight = array[0].w;
var left = array.slice(1);
left.forEach(function (element) {
var w = element.w;
var r = rand(totalWeight + w);
if (r > totalWeight) {
answer = element;
}
totalWeight += w;
});
return answer;
}
var testElements = [{n: 'fe', w: 5.33},{n: 'fi', w: 1.33},{n: 'fo', w: 10}, {n: 'fum', w: 3.33}];
var runs = 100000;
var num = runs;
var results = {fe:0, fi:0, fo:0, fum:0};
while (num--) {
var answer = randomSample(testElements);
results[answer.n]++;
}
Object.keys(results).forEach(function (key) {
results[key] = results[key] / runs * 100;
});
console.log(results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment