bkovitz
2019-3-5 11:08:54

@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.


soegaard2
2019-3-5 11:11:28

@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


mark.warren
2019-3-5 11:14:07

@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.


bkovitz
2019-3-5 11:16:45

Thanks! Now checking out discrete-dist. I’d love to be rid of that linear search.


bkovitz
2019-3-5 11:23:09

Wow, totally easy!


bkovitz
2019-3-5 11:28:00

Wow, I need to spend some time browsing through the math library.


soegaard2
2019-3-5 11:32:18

There are some nifty things.


bkovitz
2019-3-5 11:48:47

@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.