swift - 设置 GKARC4RandomSource 的种子

标签 swift random gamekit

我正在使用 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

关于swift - 设置 GKARC4RandomSource 的种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43308951/

相关文章:

random - GO:操纵随机生成的 float64

c - rand() 函数每次产生相同的输出 C

java - 还记得随机种子中的位置(?)吗?

ios - 不兼容的指针类型将 'NSArray<GKPlayer *> *' 发送到类型为 'NSArray<NSString*> * _Nonnull' 的参数

ios - 默认游戏中心 View Controller 中的成就顺序

ios - 为什么发布通知会导致崩溃?

ios - 在 AppDelegate 中模态呈现来自 UITabBarController 的 VC

uitableview - 在 Swift 的嵌入式 tableView 中准备 segue

ios - 自定义初始化方法

ios - 将 AVPlayerItem 保存到文档目录