Vcsn  2.2
Be Rational
random.hh
Go to the documentation of this file.
1 #pragma once
2 
3 #include <random>
4 #include <iterator>
5 
6 namespace vcsn
7 {
8  // Based on https://gist.github.com/cbsmith/5538174.
9  template <typename RandomGenerator>
11  {
12  random_selector(RandomGenerator& g)
13  : gen_(g)
14  {}
15 
17  template <typename Iter>
18  Iter select(Iter start, Iter end)
19  {
20  auto dis
21  = std::uniform_int_distribution<>(0, std::distance(start, end) - 1);
22  std::advance(start, dis(gen_));
23  return start;
24  }
25 
27  template <typename Iter>
28  Iter operator()(Iter start, Iter end)
29  {
30  return select(start, end);
31  }
32 
34  template <typename Container>
35  auto operator()(const Container& c) -> decltype(*std::begin(c))
36  {
37  return *select(std::begin(c), std::end(c));
38  }
39 
41  template <typename Container>
42  auto pop(Container& c) -> typename Container::value_type
43  {
44  auto i = select(std::begin(c), std::end(c));
45  auto res = *i;
46  c.erase(i);
47  return res;
48  }
49 
50  private:
51  RandomGenerator& gen_;
52  };
53 
54  template <typename RandomGenerator>
56  make_random_selector(RandomGenerator& g)
57  {
58  return g;
59  }
60 }
Definition: a-star.hh:8
Iter operator()(Iter start, Iter end)
A randomly selected iterator in [start, end).
Definition: random.hh:28
random_selector(RandomGenerator &g)
Definition: random.hh:12
random_selector< RandomGenerator > make_random_selector(RandomGenerator &g)
Definition: random.hh:56
RandomGenerator & gen_
Definition: random.hh:51
Iter select(Iter start, Iter end)
A randomly selected iterator in [start, end).
Definition: random.hh:18
auto pop(Container &c) -> typename Container::value_type
A randomly selected member of c. Remove it from c.
Definition: random.hh:42
auto operator()(const Container &c) -> decltype(*std::begin(c))
A randomly selected member of c.
Definition: random.hh:35