Skip to content

Instantly share code, notes, and snippets.

@rayfix
Last active Oct 3, 2020
Embed
What would you like to do?
// 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