Skip to content

Instantly share code, notes, and snippets.

@imbcmdth
Created December 14, 2014 18:10
Show Gist options
  • Save imbcmdth/c8214a0c5a93aba2b504 to your computer and use it in GitHub Desktop.
Save imbcmdth/c8214a0c5a93aba2b504 to your computer and use it in GitHub Desktop.
Weighted Sampling Generator
function rand (max) { return Math.random() * max; }
function *randomSample () {
var answer = yield;
var totalWeight = answer.w;
while (true) {
var next = yield answer;
var w = next.w;
var r = rand(totalWeight + w);
if (r > totalWeight) {
answer = next;
}
totalWeight += w;
}
}
var sample = randomSample();
var v, i = 1000;
sample.next();
while (i--) {
v = sample.next({n: 'elem' + i, w: rand(10)}).value;
}
console.log(v);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment