设置 GKARC4RandomSource 的种子

Setting seed of GKARC4RandomSource

我正在使用 GKARC4RandomSource(来自 GameKit)生成随机数。设置种子后,我生成了一些随机数。在同一个实例中,但在后一个实例中,我设置了完全相同的种子,并且我再次生成了一些数字。由于种子是相同的,我期待相同的数字,但这并没有发生。我错过了什么? 代码:

let randSource = GKARC4RandomSource()

    func foo() {
        print("1st sequence")
        randSource.seed = "seed".data(using: .utf8)!
        for _ in 0...10 {
            print(randSource.nextInt())
        }
    }


    func bar() {
        print("2nd sequence")
        randSource.seed = "seed".data(using: .utf8)!
        for _ in 0...10 {
            print(randSource.nextInt())
        }
    }

    foo()
    bar()

输出: 第一序列 1077893367 -527596564 188760480 -1473410833 1247450388 155479986 -1227640578 -1952625186 -1819582711 1494875350 238061911 第二序列 -815382461 1319464721 -496336642 1307036859 -1543687700 1786062933 63740842 657867659 -1908618575 360960015 75414057

documentation for GKARC4RandomSource 建议在初始化程序中使用 seed

Any two random sources initialized with the same seed data will generate the same sequence of random numbers. To replicate the behavior of an existing GKARC4Random​Source instance, read that instance’s seed property and then create a new instance by passing the resulting data to the init(seed:​) initializer.

如果您使用 init(seed:),它有效:

func foo() {
    print("1st sequence")

    let seed = "seed".data(using: .utf8)!
    let randSource = GKARC4RandomSource(seed: seed)
    for _ in 0...10 {
        print(randSource.nextInt())
    }
}


func bar() {
    print("2nd sequence")

    let seed = "seed".data(using: .utf8)!
    let randSource = GKARC4RandomSource(seed: seed)
    for _ in 0...10 {
        print(randSource.nextInt())
    }
}

foo()
bar()

输出

1st sequence
-907495547
-1853348607
-891423934
-1115481462
-1946427034
-1478051111
1807292425
525674909
-1209007346
-1508915292
-1396618639
2nd sequence
-907495547
-1853348607
-891423934
-1115481462
-1946427034
-1478051111
1807292425
525674909
-1209007346
-1508915292
-1396618639