OR-Tools  9.1
random.h
Go to the documentation of this file.
1// Copyright 2010-2021 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14#ifndef OR_TOOLS_BASE_RANDOM_H_
15#define OR_TOOLS_BASE_RANDOM_H_
16
17#include <random>
18#include <string>
19
20#include "absl/random/random.h"
22
23namespace operations_research {
24
25// A wrapper around std::mt19937. Called ACMRandom for historical reasons.
26class ACMRandom {
27 public:
28 explicit ACMRandom(int32_t seed) : generator_(seed) {}
29
30 // Unbounded generators.
31 uint32_t Next();
32 uint64_t Next64();
33 uint64_t Rand64() { return Next64(); }
34 uint64_t operator()() { return Next64(); }
35
36 // Bounded generators.
37 uint32_t Uniform(uint32_t n);
38 uint64_t operator()(uint64_t val_max);
39
40 // Seed management.
41 void Reset(int32_t seed) { generator_.seed(seed); }
42 static int32_t HostnamePidTimeSeed();
43 static int32_t DeterministicSeed();
44
45 // C++11 goodies.
46 typedef int64_t difference_type;
47 typedef uint64_t result_type;
48 static constexpr result_type min() { return 0; }
49 static constexpr result_type max() { return kuint32max; }
50
51 private:
52 std::mt19937 generator_;
53};
54
55class MTRandom : public ACMRandom {
56 public:
57 explicit MTRandom(int32_t seed) : ACMRandom(seed) {}
58 // MTRandom also supports a std::string seed.
59 explicit MTRandom(const std::string& str_seed)
60 : ACMRandom(GenerateInt32SeedFromString(str_seed)) {}
61
63
64 private:
65 int32_t GenerateInt32SeedFromString(const std::string& str) {
66 uint32_t seed = 1234567;
67 for (size_t i = 0; i < str.size(); ++i) {
68 seed *= 1000003; // prime
69 seed += static_cast<uint32_t>(str[i]);
70 }
71 return seed >> 1; // Will fit into an int32_t.
72 }
73};
74
75} // namespace operations_research
76
77#endif // OR_TOOLS_BASE_RANDOM_H_
static int32_t HostnamePidTimeSeed()
Definition: random.cc:59
void Reset(int32_t seed)
Definition: random.h:41
static int32_t DeterministicSeed()
Definition: random.cc:93
ACMRandom(int32_t seed)
Definition: random.h:28
static constexpr result_type max()
Definition: random.h:49
static constexpr result_type min()
Definition: random.h:48
uint32_t Uniform(uint32_t n)
Definition: random.cc:40
MTRandom(const std::string &str_seed)
Definition: random.h:59
MTRandom(int32_t seed)
Definition: random.h:57
static const uint32_t kuint32max
Collection of objects used to extend the Constraint Solver library.