summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/random-weight.h
blob: 7b9995520f90e457ff686c4132adf2cc23de2b8c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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