algorithms
2.2.0
Framework-independent algorithms for the EIC
Toggle main menu visibility
Loading...
Searching...
No Matches
random.h
Go to the documentation of this file.
1
#pragma once
2
3
#include <cstdint>
4
#include <functional>
5
#include <vector>
6
7
namespace
algorithms::detail
{
8
9
// Auto-refreshing cached sequence from an underlying random engine allowing for multiple instances
10
// to be evaluated in parallel. Specs:
11
// - GenFunc is required to return N random numbers between 0 and
12
// std::numeric_limits<uint_fast64_t>::max()
13
// - GenFunc is responsible to deal with possible simultaneous access by multiple
14
// instances of CachedBitGenerator (required to be thread-safe).
15
// - The owner of a CachedGenerator instance is responsible to prevent parallel
16
// calls to ::operator()
17
// Implements the uniform_random_bit_generator concept
18
class
CachedBitGenerator
{
19
public
:
20
using
result_type
= uint_fast64_t;
21
using
GenFunc
= std::function<std::vector<result_type>(
size_t
/* N */
)>;
22
CachedBitGenerator
(
const
GenFunc
& gen,
const
size_t
cache_size)
23
// index starts at the end of the (empty) cache to force an immediate refresh
24
// on first access
25
: m_gen{gen}, m_cache(cache_size), m_index{cache_size} {}
26
27
result_type
operator()
() {
28
if
(m_index >= m_cache.size()) {
29
refresh();
30
}
31
return
m_cache[m_index++];
32
}
33
34
static
constexpr
result_type
min
() {
return
0; }
35
static
constexpr
result_type
max
() {
return
std::numeric_limits<result_type>::max(); }
36
37
private
:
38
void
refresh() {
39
m_cache = m_gen(m_cache.size());
40
m_index = 0;
41
}
42
43
GenFunc
m_gen;
44
std::vector<CachedBitGenerator::result_type> m_cache;
45
size_t
m_index;
46
};
47
48
}
// namespace algorithms::detail
algorithms::detail::CachedBitGenerator::GenFunc
std::function< std::vector< result_type >(size_t)> GenFunc
Definition
random.h:21
algorithms::detail::CachedBitGenerator::CachedBitGenerator
CachedBitGenerator(const GenFunc &gen, const size_t cache_size)
Definition
random.h:22
algorithms::detail::CachedBitGenerator::max
static constexpr result_type max()
Definition
random.h:35
algorithms::detail::CachedBitGenerator::min
static constexpr result_type min()
Definition
random.h:34
algorithms::detail::CachedBitGenerator::operator()
result_type operator()()
Definition
random.h:27
algorithms::detail::CachedBitGenerator::result_type
uint_fast64_t result_type
Definition
random.h:20
algorithms::detail
Definition
algorithm.h:183
core
include
algorithms
detail
random.h
Generated by
1.17.0