Last active
December 29, 2019 14:36
-
-
Save nucleartide/1633a534162d313fd6b0dc2a23a682b1 to your computer and use it in GitHub Desktop.
This file contains 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
function weighted_choice(choices) | |
local total_weight = 0 | |
local thresholds = {} | |
for choice, weight in pairs(choices) do | |
add(thresholds, {total_weight, choice}) | |
total_weight += weight | |
end | |
local selection = rnd(total_weight) | |
for i=1,#thresholds-1 do | |
local tuple, next_tuple = thresholds[i], thresholds[i+1] | |
local lower_bound, choice, upper_bound = tuple[1], tuple[2], next_tuple[1] | |
if lower_bound <= selection and selection < upper_bound then | |
return choice | |
end | |
end | |
local choice = thresholds[#thresholds][2] | |
return choice | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment