From 5c15e6abda97c19829d5b2b348b422f3857b42f7 Mon Sep 17 00:00:00 2001 From: Robert Vollmert Date: Fri, 13 Nov 2009 23:34:11 +0100 Subject: Implement weighted choice from array. --- crawl-ref/source/random-weight.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 crawl-ref/source/random-weight.h (limited to 'crawl-ref/source/random-weight.h') diff --git a/crawl-ref/source/random-weight.h b/crawl-ref/source/random-weight.h new file mode 100644 index 0000000000..7b9995520f --- /dev/null +++ b/crawl-ref/source/random-weight.h @@ -0,0 +1,22 @@ +#ifndef RANDOM_WEIGHT_H +#define RANDOM_WEIGHT_H + +template +T* random_choose_weighted(std::vector > choices) +{ + int total = 0; + for (unsigned int i = 0; i < choices.size(); i++) + total += choices[i].second; + int r = random2(total); + int sum = 0; + for (unsigned int i = 0; i < choices.size(); i++) + { + sum += choices[i].second; + if (sum > r) + return (&choices[i].first); + } + return (NULL); +} + +#endif + -- cgit v1.2.3-54-g00ecf