File: random-weight.h

package info (click to toggle)
crawl 2%3A0.7.1-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 30,420 kB
  • ctags: 23,018
  • sloc: cpp: 244,317; ansic: 16,144; perl: 2,214; makefile: 984; python: 488; objc: 250; ruby: 200; sh: 140
file content (28 lines) | stat: -rw-r--r-- 652 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef RANDOM_WEIGHT_H
#define RANDOM_WEIGHT_H

/*
 * Weighted choice.
 *
 * Weights are assumed to be non-negative, but are allowed to be zero.
 * Returns NULL if nothing found, i.e., if all weights are zero.
 */
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