Cytopia  0.3
A city building simulation game
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Randomizer.hxx
Go to the documentation of this file.
1 #ifndef RANDOMIZER_HXX_
2 #define RANDOMIZER_HXX_
3 
4 #include <random>
5 #include <iterator>
6 #include <algorithm>
7 #include "../util/Singleton.hxx"
8 
9 class Randomizer : public Singleton<Randomizer>
10 {
11  static thread_local std::mt19937 generator;
12 
13  template <typename IntType> using UniformIntDist = std::uniform_int_distribution<IntType>;
14 
15 public:
16  Randomizer() = default;
17 
18  template <typename Iterator> void shuffle(Iterator begin, Iterator end) { std::shuffle(begin, end, generator); }
19 
29  template <typename Iterator> Iterator choose(Iterator begin, Iterator end)
30  {
31  using DiffType = typename std::iterator_traits<Iterator>::difference_type;
32  DiffType upper{std::distance(begin, end) - 1};
33  UniformIntDist<DiffType> distn{DiffType{0}, upper};
34  std::advance(begin, distn(generator));
35  return begin;
36  }
37 };
38 
39 #endif
Randomizer::choose
Iterator choose(Iterator begin, Iterator end)
Pick random item from container.
Definition: Randomizer.hxx:29
Randomizer::Randomizer
Randomizer()=default
Randomizer::shuffle
void shuffle(Iterator begin, Iterator end)
Definition: Randomizer.hxx:18
Randomizer::generator
static thread_local std::mt19937 generator
Definition: Randomizer.hxx:11
Singleton
Abstract Singleton implementation.
Definition: Singleton.hxx:8
Randomizer
Definition: Randomizer.hxx:9
Randomizer::UniformIntDist
std::uniform_int_distribution< IntType > UniformIntDist
Definition: Randomizer.hxx:13