Vcsn  2.0
Be Rational
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
random.hh
Go to the documentation of this file.
1 #ifndef VCSN_MISC_RANDOM_HH
2 # define VCSN_MISC_RANDOM_HH
3 
4 # include <random>
5 # include <iterator>
6 
7 # include <vcsn/misc/attributes.hh>
8 
9 namespace vcsn
10 {
11 
12  // Based on https://gist.github.com/cbsmith/5538174.
13  template <typename RandomGenerator = std::default_random_engine>
15  {
16  random_selector(const RandomGenerator& g = RandomGenerator())
17  : gen_(g)
18  {}
19 
21  template <typename Iter>
22  Iter select(Iter start, Iter end)
23  {
24  std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
25  std::advance(start, dis(gen_));
26  return start;
27  }
28 
30  template <typename Iter>
31  Iter operator()(Iter start, Iter end)
32  {
33  return select(start, end);
34  }
35 
37  template <typename Container>
38  auto operator()(const Container& c) -> decltype(*std::begin(c))
39  {
40  return *select(std::begin(c), std::end(c));
41  }
42 
44  template <typename Container>
45  auto pop(Container& c) -> typename Container::value_type
46  {
47  auto i = select(std::begin(c), std::end(c));
48  auto res = *i;
49  c.erase(i);
50  return res;
51  }
52 
53  private:
54  RandomGenerator gen_;
55  };
56 
57 
58  template <typename RandomGenerator = std::default_random_engine>
59  struct random_selector<RandomGenerator>
60  make_random_selector(const RandomGenerator& g)
61  ATTRIBUTE_PURE;
62 
63  template <typename RandomGenerator>
64  struct random_selector<RandomGenerator>
65  make_random_selector(const RandomGenerator& g)
66  {
67  return g;
68  }
69 
70 } // !vcsn
71 
72 #endif // !VCSN_MISC_RANDOM_HH
struct random_selector< RandomGenerator > make_random_selector(const RandomGenerator &g) ATTRIBUTE_PURE
Definition: random.hh:65
random_selector(const RandomGenerator &g=RandomGenerator())
Definition: random.hh:16
auto pop(Container &c) -> typename Container::value_type
A randomly selected member of c. Remove it from c.
Definition: random.hh:45
RandomGenerator gen_
Definition: random.hh:54
Iter operator()(Iter start, Iter end)
A randomly selected iterator in [start, end).
Definition: random.hh:31
auto operator()(const Container &c) -> decltype(*std::begin(c))
A randomly selected member of c.
Definition: random.hh:38
Iter select(Iter start, Iter end)
A randomly selected iterator in [start, end).
Definition: random.hh:22