OR-Tools  8.2
random.h
Go to the documentation of this file.
1// Copyright 2010-2018 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 seed) : generator_(seed) {}
29
30 // Unbounded generators.
31 uint32 Next();
32 uint64 Next64();
33 uint64 Rand64() { return Next64(); }
34 uint64 operator()() { return Next64(); }
35
36 // Bounded generators.
38 uint64 operator()(uint64 val_max);
39
40 // Seed management.
41 void Reset(int32 seed) { generator_.seed(seed); }
43 static int32 DeterministicSeed();
44
45 // C++11 goodies.
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 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 GenerateInt32SeedFromString(const std::string& str) {
66 uint32 seed = 1234567;
67 for (size_t i = 0; i < str.size(); ++i) {
68 seed *= 1000003; // prime
69 seed += static_cast<uint32>(str[i]);
70 }
71 return seed >> 1; // Will fit into an int32.
72 }
73};
74
75} // namespace operations_research
76
77#endif // OR_TOOLS_BASE_RANDOM_H_
void Reset(int32 seed)
Definition: random.h:41
static int32 DeterministicSeed()
Definition: random.cc:92
static constexpr result_type max()
Definition: random.h:49
uint32 Uniform(uint32 n)
Definition: random.cc:40
static constexpr result_type min()
Definition: random.h:48
static int32 HostnamePidTimeSeed()
Definition: random.cc:58
MTRandom(const std::string &str_seed)
Definition: random.h:59
unsigned int uint32
int int32
int64_t int64
static const uint32 kuint32max
uint64_t uint64
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...