@mark.warren @hoshom @greg I just happened to write a weighted-choice
function a couple weeks ago, and saw your conversation just now. Here’s what I came up with. It just makes a list with cumulative weights, chooses a random number, and then steps through the list. I’d love to know if there’s a better way. My application for this needs to call it a lot, so it should be efficient.
@bkovitz Don’t know about better - but you can use (discrete-dist xs '(2 5 3))
to create a distribution with given weights, and then use (sample d n)
to generate n
samples from the distribtion d
. See the example here: https://docs.racket-lang.org/math/Finite_Distribution_Families.html?q=math
@bkovitz I ended up converting the list to a hash of ranges and then searching the hash for the relevant range. But I think @soegaard2 probably has a better idea.
Thanks! Now checking out discrete-dist
. I’d love to be rid of that linear search.
Wow, totally easy!
Wow, I need to spend some time browsing through the math
library.
There are some nifty things.
@soegaard2 There sure are! And discrete-dist
is 2x as fast as weighted-choice-by
—probably faster with larger sets of items to choose from.