Created
October 17, 2016 23:20
-
-
Save koozdra/f60b89511173a72cb95ab6f0dd54cbc4 to your computer and use it in GitHub Desktop.
Modification free selection of random weighted element
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
| 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