master
ブランチ master
cpputils / src / util / random.cc
2.2 KB、77行 生 Blame 履歴
1/*
2# 076 Free License
3
4Copyright (c) テクニカル諏訪子
5
6Permission is hereby granted to any person obtaining a copy of the software
7C++ Utils (the "Software") to use, modify, merge, copy, publish, distribute,
8sublicense, and/or sell copies of the Software, subject to the following conditions:
9
10 1. **Origin Attribution**:
11 - You must not misrepresent the origin of the Software; you must not claim
12 you created the original Software.
13 2. **Notice Preservation**:
14 - This license and the above copyright notice must remain intact in all copies
15 of the source code.
16
17THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
19PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
21CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
22OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23*/
24#include <util/random.hh>
25#include <cmath>
26#include <chrono>
27
28namespace util::rand {
29 u32 randState[4];
30
31 static inline u32 leftRot(const u32 x, i32 k) {
32 return (x << k) | (x >> (32 - k));
33 }
34
35 u32 xoshiro128() {
36 const u32 res = leftRot(randState[1] * 5, 7) * 9;
37 const u32 t = randState[1] << 9;
38
39 randState[2] ^= randState[0];
40 randState[3] ^= randState[1];
41 randState[1] ^= randState[2];
42 randState[0] ^= randState[3];
43
44 randState[2] ^= t;
45 randState[3] = leftRot(randState[3], 11);
46
47 return res;
48 }
49
50 i32 getValue(i32 min, i32 max) {
51 u32 range = static_cast<u32>(max - min + 1);
52 return min + (xoshiro128() % range);
53 }
54
55 static u32 splitmix32(u32 &x) {
56 u32 z = (x += 0x9e3779b9);
57 z = (z ^ (z >> 16)) * 0x85ebca6b;
58 z = (z ^ (z >> 13)) * 0xc2b2ae35;
59 return z ^ (z >> 16);
60 }
61
62 //////////////////////
63
64 void Seed(u32 seed) {
65 for (int i = 0; i < 4; i++) randState[i] = splitmix32(seed);
66 }
67
68 i32 GetRandom(i32 min, i32 max) {
69 if (min > max) {
70 i32 tmp = max;
71 max = min;
72 min = tmp;
73 }
74
75 return getValue(min, max);
76 }
77} // namespace util::rand