diff options
author | Robert Vollmert <rvollmert@gmx.net> | 2009-11-13 23:34:11 +0100 |
---|---|---|
committer | Robert Vollmert <rvollmert@gmx.net> | 2009-11-14 00:45:06 +0100 |
commit | 5c15e6abda97c19829d5b2b348b422f3857b42f7 (patch) | |
tree | b269e5a5a439ee02d9d5e84bc94adc78c9769d75 /crawl-ref/source/random-weight.h | |
parent | 93534c22120fb7693535a4d341d94158469674ad (diff) | |
download | crawl-ref-5c15e6abda97c19829d5b2b348b422f3857b42f7.tar.gz crawl-ref-5c15e6abda97c19829d5b2b348b422f3857b42f7.zip |
Implement weighted choice from array.
Diffstat (limited to 'crawl-ref/source/random-weight.h')
-rw-r--r-- | crawl-ref/source/random-weight.h | 22 |
1 files changed, 22 insertions, 0 deletions
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 <typename T> +T* random_choose_weighted(std::vector<std::pair<T, int> > 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 + |