Skip to content

Instantly share code, notes, and snippets.

@tripzilch
Last active October 6, 2023 16:28
Show Gist options
  • Save tripzilch/522acfe5c1f3ac97abc3a216d1fa4679 to your computer and use it in GitHub Desktop.
Save tripzilch/522acfe5c1f3ac97abc3a216d1fa4679 to your computer and use it in GitHub Desktop.
pick randomly from a list with weighted probabilities
// 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']
);
@josvromans
Copy link

Great! thanks Piter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment