This repository has been archived on 2020-04-08. You can view files and clone it, but cannot push or open issues or pull requests.
Files
Indoor/math/DrawList.h
kazu 9947dced15 added several grid-walks
added new helper methods/classes (e.g. for heading)
new test cases
optimize the dijkstra
cleanups/refactoring
added timed-benchmarks to the log
many more...
2016-01-24 18:59:06 +01:00

83 lines
1.6 KiB
C++

#ifndef DRAWLIST_H
#define DRAWLIST_H
#include <vector>
#include <random>
/**
* add elements of a certain probability
* and randomly draw from them
*/
template <typename T> class DrawList {
/** one entry */
struct Entry {
/** the user element */
T element;
/** the cumulative probability up to this element */
double cumProbability;
/** ctor */
Entry(T element, const double cumProbability) : element(element), cumProbability(cumProbability) {;}
/** compare for searches */
bool operator < (const double val) const {return cumProbability < val;}
};
private:
/** current cumulative probability */
double cumProbability;
/** all contained elements */
std::vector<Entry> elements;
/** random number generator */
std::minstd_rand gen;
public:
/** ctor */
DrawList() : cumProbability(0) {
;
}
/** reset */
void reset() {
cumProbability = 0;
elements.clear();
}
/** add a new user-element and its probability */
void add(T element, const double probability) {
cumProbability += probability;
elements.push_back(Entry(element, cumProbability));
}
/** get a random element based on its probability */
T get() {
// generate random number between [0:cumProbability]
std::uniform_real_distribution<> dist(0, cumProbability);
// get a random value
const double rndVal = dist(gen);
// binary search for the matching entry O(log(n))
const auto tmp = std::lower_bound(elements.begin(), elements.end(), rndVal);
return (*tmp).element;
}
/** get the current, cumulative probability */
double getCumProbability() const {
return cumProbability;
}
};
#endif // DRAWLIST_H