Swift 4.2+ seeding a random number generator

前端 未结 4 759
萌比男神i
萌比男神i 2021-02-13 17:19

I\'m trying to generate seeded random numbers with Swift 4.2+, with the Int.random() function, however there is no given implementation that allows for the random n

4条回答
  •  -上瘾入骨i
    2021-02-13 17:30

    Here's alternative to the answer from RPatel99 that accounts GKRandom values range.

    import GameKit
    
    struct ArbitraryRandomNumberGenerator : RandomNumberGenerator {
    
        mutating func next() -> UInt64 {
            // GKRandom produces values in [INT32_MIN, INT32_MAX] range; hence we need two numbers to produce 64-bit value.
            let next1 = UInt64(bitPattern: Int64(gkrandom.nextInt()))
            let next2 = UInt64(bitPattern: Int64(gkrandom.nextInt()))
            return next1 ^ (next2 << 32)
        }
    
        init(seed: UInt64) {
            self.gkrandom = GKMersenneTwisterRandomSource(seed: seed)
        }
    
        private let gkrandom: GKRandom
    }
    

提交回复
热议问题