-
-
Save tripzilch/522acfe5c1f3ac97abc3a216d1fa4679 to your computer and use it in GitHub Desktop.
pick randomly from a list with weighted probabilities
This file contains 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
// by Piter Pasma | |
// also see https://twitter.com/piterpasma/status/1591727290802741248 | |
// pick from a weighted list of parameters (81 chars) | |
pk=(...w)=>(t=0,w.map(x=>x[0]=(t+=x[0])),t=R(t),w.filter(x=>t<x[0])[0].slice(1)); | |
// pick from a weighted list of parameters (76 chars) | |
pk=(...w)=>(t=0,w.map(x=>x[0]=(t+=x[0])),t=R(t),w.find(x=>t<x[0]).slice(1)); | |
// usage | |
console.log(pk( | |
[5,'aap'], | |
[25,'noot'], | |
[7,'mies'], | |
[1,'boom'], | |
[13,'roos'], | |
)); | |
// outputs | |
// ['noot'] | |
// sample usage for parameters | |
[$fxhashFeatures.bgcolor, bgcolor] = pk( | |
[3,'brown','#886600'] | |
[12,'yellow','#ffff00'] | |
[37,'white','#ffffff'] | |
[6,'blue','#3366ff'] | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great! thanks Piter