Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Created May 17, 2020 02:21
Show Gist options
  • Save nicklockwood/cf1fde3eb24602883c17f94e63e490bc to your computer and use it in GitHub Desktop.
Save nicklockwood/cf1fde3eb24602883c17f94e63e490bc to your computer and use it in GitHub Desktop.
RNG not working as expected
struct RNG: RandomNumberGenerator {
let modulus: UInt64 = 233_280
let multiplier: UInt64 = 9301
let increment: UInt64 = 49297
var seed: UInt64 = 0
mutating func next() -> UInt64 {
seed = (seed * multiplier + increment) % modulus
return seed
}
}
var rng = RNG(seed: 1000)
var numbers = [0, 1, 2, 3, 4, 5, 6]
print("### next() ###")
for _ in 0 ..< 5 {
print(rng.next())
}
print("### next(upperBound:) ###")
for _ in 0 ..< 5 {
print(rng.next(upperBound: UInt(numbers.count)))
}
print("### random(in:) ###")
for _ in 0 ..< 5 {
print(numbers[Int.random(in: numbers.indices, using: &rng)])
}
print("### randomElement() ###")
for _ in 0 ..< 5 {
print(numbers.randomElement(using: &rng)!)
}
@nicklockwood
Copy link
Author

The upperBound usage is consistent with the rest of Swift.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment