Last active
October 3, 2020 22:22
-
-
Save rayfix/656d044c87dfc059ad301d378fe28e33 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Algorithm from https://en.wikipedia.org/wiki/Permuted_congruential_generator | |
struct PRNG: RandomNumberGenerator { | |
var state: UInt64 = 0x4d595df4d0f33173 | |
let multiplier: UInt64 = 6364136223846793005 | |
let increment: UInt64 = 1442695040888963407 | |
init(seed: UInt64) { | |
state = seed &+ increment | |
_ = next() | |
} | |
private func rotr32(x: UInt32, r: UInt32) -> UInt32 { | |
(x &>> r) | x &<< ((~r &+ 1) & 31) | |
} | |
@inlinable mutating func next32() -> UInt32 { | |
var x = state | |
let count = UInt32(x &>> 59) | |
state = x &* multiplier &+ increment | |
x ^= x &>> 18 | |
return rotr32(x: UInt32(truncatingIfNeeded: x &>> 27), | |
r: count) | |
} | |
mutating func next() -> UInt64 { | |
UInt64(next32()) << 32 | UInt64(next32()) | |
} | |
} | |
var randomSource = PRNG(seed: 1234) | |
// SystemRandomNumberGenerator() | |
for _ in 1...10 { | |
print(Int.random(in: 1...10, using: &randomSource)) | |
} | |
var prng2 = PRNG(seed: 12346) | |
for _ in 1...10 { | |
print(Int.random(in: 1...10, using: &randomSource)) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment