Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

seeding arc4random() in iOS

From what I can gather arc4random() generates much better random numbers than rand() does, however I haven't seen a way to seed it, and I would like to just like using srand(). Is there a way?

like image 319
andrewz Avatar asked Nov 23 '10 07:11

andrewz


2 Answers

That's not what arc4random is designed to do. As the documentation states:

The arc4random() function provides a high quality 32-bit pseudo-random number very quickly. arc4random() seeds itself on a regular basis from the kernel strong random number subsystem described in random(4).

Since it is re-seeds itself from an entropy source anyway, you gain nothing by seeding it manually, and in fact, such a method does not exist.

like image 174
Joey Avatar answered Nov 05 '22 20:11

Joey


You can actually do this in iOS 9.

import GameKit

let source = GKARC4RandomSource(seed: "hello world".data(using: .utf8)!)
source.dropValues(1024)
source.nextInt() // <-- your number

According to the docs:

Arc4 based random sources have repeatable initial sequences. If used for obfuscation you should drop N values from the start, where N should be any number larger than 768 to ensure the initial sequence is flushed.

So as long as you use the same seed data (obviously without using ! in production code) and the same number of dropped values, you'll get the same results.

like image 8
Sam Soffes Avatar answered Nov 05 '22 19:11

Sam Soffes