Skip to content

Instantly share code, notes, and snippets.

@amalloy
Created December 28, 2016 00:09
Show Gist options
  • Save amalloy/3c238d87c6ce20ff27a457202ed1e8a6 to your computer and use it in GitHub Desktop.
Save amalloy/3c238d87c6ce20ff27a457202ed1e8a6 to your computer and use it in GitHub Desktop.
template<typename T, typename Iterator>
T* random_choose_weighted(Iterator xs, function<int (const T&)> weight)
{
int totalweight = 0;
const T* result = nullptr;
while (xs) {
T* curr = *xs;
int cweight = weight(*curr);
totalweight += cweight;
if (x_chance_in_y(cweight, totalweight)) {
result = curr;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment