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