Created
December 14, 2014 18:10
-
-
Save imbcmdth/c8214a0c5a93aba2b504 to your computer and use it in GitHub Desktop.
Weighted Sampling Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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