-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomSelector.h
More file actions
41 lines (34 loc) · 1.03 KB
/
RandomSelector.h
File metadata and controls
41 lines (34 loc) · 1.03 KB
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
34
35
36
37
38
39
40
41
#pragma once
#ifndef __RANDOMSELECTOR__
#define __RANDOMSELECTOR__
#include <random>
#include <iterator>
template <typename RandomGenerator = std::default_random_engine>
struct RandomSelector
{
//On most platforms, you probably want to use std::random_device("/dev/urandom")()
RandomSelector(RandomGenerator g = RandomGenerator(std::random_device()()))
: gen(g) {}
template <typename Iter>
Iter select(Iter start, Iter end)
{
std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
std::advance(start, dis(gen));
return start;
}
//convenience function
template <typename Iter>
Iter operator()(Iter start, Iter end)
{
return select(start, end);
}
//convenience function that works on anything with a sensible begin() and end(), and returns with a ref to the value type
template <typename Container>
auto operator()(const Container& c) -> decltype(*begin(c)) &
{
return *select(begin(c), end(c));
}
private:
RandomGenerator gen;
};
#endif // __RANDOMSELECTOR__