Skip to content

Instantly share code, notes, and snippets.

@nucleartide
Last active December 29, 2019 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nucleartide/1633a534162d313fd6b0dc2a23a682b1 to your computer and use it in GitHub Desktop.
Save nucleartide/1633a534162d313fd6b0dc2a23a682b1 to your computer and use it in GitHub Desktop.
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