Skip to content

Instantly share code, notes, and snippets.

@koozdra
Created October 17, 2016 23:20
Show Gist options
  • Select an option

  • Save koozdra/f60b89511173a72cb95ab6f0dd54cbc4 to your computer and use it in GitHub Desktop.

Select an option

Save koozdra/f60b89511173a72cb95ab6f0dd54cbc4 to your computer and use it in GitHub Desktop.
Modification free selection of random weighted element
const d = {
share: 5,
promote: 6,
engage: 11,
discover: 1
}
const total = _(d).values().sum();
const buckets = _(d)
.mapValues(v => v / total)
.toPairs()
.value();
function randomBucket(buckets, r){
const [name, perc] = _.head(buckets);
if (r - perc < 0) return name;
return randomBucket(_.tail(buckets), r - perc)
}
console.log(total);
console.log(d);
console.log(buckets);
console.log(randomBucket(buckets, Math.random()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment