Website Summary Files Commits Branches @commit @diff @stats
path: root / gctest / src / weighted_action.h
blob: 4bcdd6f2df5e4620b473809217d4dcbd82d780f7 (plain) (blame)
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
29
30
31
32
33
#pragma once
#include <functional>
#include <random>
#include <vector>

template <typename Result, typename Generator>
class WeightedActionTable
{
public:
    WeightedActionTable(Generator* generator) : m_Generator(generator) {}

    typedef std::function<Result()> ActionCallback;

    void AddAction(ActionCallback action, unsigned weight)
    {
        m_Actions.emplace_back(action);
        m_Weights.emplace_back(weight);
        m_Distribution =
            std::discrete_distribution(m_Weights.begin(), m_Weights.end());
    }

    Result RunRandomAction()
    {
        auto random = m_Distribution(*m_Generator);
        return m_Actions[random]();
    }

private:
    std::vector<ActionCallback> m_Actions;
    std::vector<unsigned> m_Weights;
    Generator* m_Generator;
    std::discrete_distribution<int> m_Distribution;
};