Swift 4.2+ seeding a random number generator

前端 未结 4 760
萌比男神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:49

    I ended up using srand48() and drand48() to generate a pseudo-random number with a seed for a specific test.

    class SeededRandomNumberGenerator : RandomNumberGenerator {
    
        let range: ClosedRange = Double(UInt64.min) ... Double(UInt64.max)
    
        init(seed: Int) {
            // srand48() — Pseudo-random number initializer
            srand48(seed)
        }
    
        func next() -> UInt64 {
            // drand48() — Pseudo-random number generator
            return UInt64(range.lowerBound + (range.upperBound - range.lowerBound) * drand48())
        }
        
    }
    

    So, in production the implementation uses the SystemRandomNumberGenerator but in the test suite it uses the SeededRandomNumberGenerator.

    Example:

    let messageFixtures: [Any] = [
        "a string",
        ["some", ["values": 456]],
    ]
    
    var seededRandomNumberGenerator = SeededRandomNumberGenerator(seed: 13)
    
    func randomMessageData() -> Any {
        return messageFixtures.randomElement(using: &seededRandomNumberGenerator)!
    }
    
    // Always return the same element in the same order
    randomMessageData() //"a string"
    randomMessageData() //["some", ["values": 456]]
    randomMessageData() //["some", ["values": 456]]
    randomMessageData() //["some", ["values": 456]]
    randomMessageData() //"a string"
    

提交回复
热议问题