dimanche 29 mars 2020

Array shuffle(using: RandomNumberGenerator) strange behavior

Since Xcode 11.4 the array doesn't get shuffled at all (regardless of the seed) when using the second implementation of the next function.

I don't get why, since both functions generate random numbers, even though the first only populates the least significant 32 bits of the random Int64.

You can try this minimal example in Swift Playgrounds, commenting out one of the two functions.

    import GameplayKit

    struct SeededGenerator: RandomNumberGenerator {
        static var shared: SeededGenerator?

        let seed: UInt64
        let generator: GKMersenneTwisterRandomSource

        init(seed: UInt64) {
            self.seed = seed
            generator = GKMersenneTwisterRandomSource(seed: seed)
        }

        // New alternative found to be working
        mutating func next() -> UInt64 {
            let next1 = UInt64(bitPattern: Int64(generator.nextInt()))
            let next2 = UInt64(bitPattern: Int64(generator.nextInt()))
            return next1 | (next2 << 32)
        }

        // Code previously in use that doesn't work anymore.
        mutating func next() -> UInt64 {
            return UInt64(bitPattern: Int64(abs(generator.nextInt())))
        }
    }

    var gen = SeededGenerator(seed: 234)

    var array = ["1", "2", "3"]
    array.shuffle(using: &gen)



Aucun commentaire:

Enregistrer un commentaire