Trouble understanding random number generator

I am looking at the code for an app that is a dice rolling app. It's supposed to generate a random number from 1 to 6, which will correspond with the face of each die (dice cube).

However, the code uses arc4random(), which I've seen before but do not understand. (I've only used native Swift random number generators in the past.)

I do not at all understand how this code manages to generate a random number from one to six; moreover, I'm having trouble actually reading the code. Could someone please help me understand how this code (below) generates a random number from one to six - and how I should actually "read" this code? I'm a beginner so a beginner-friendly explanation would be very much appreciated. Thank you:

 * Randomly generates a Int from 1 to 6
*/
func randomDiceValue() -> Int {
    // Generate a random Int32 using arc4Random
    let randomValue = 1 + arc4random() % 6
    
    // Return a more convenient Int, initialized with the random value
    return Int(randomValue)
}

PLEASE NOTE: the part that I do not at all understand is:

1 + arc4random() % 6

arc4random is a random generator function. From the History section, it got that name because it uses an algorithm called RC4, or ARC4. This function generates a 32-bit random number. So now you get a random number between 0 and 4294967295 (inclusive). You then restrict it's values to [0, 5] using % 6, and then add 1 later. Hope that helps.


That said, it's a very dated way to generate random number. Not to mention that you don't get a uniform distribution. I'd suggest that you do:

Int.random(in: 1...6)
4 Likes

Well, it used to. On macOS and the BSDs it now uses different, cryptographically-secure algorithms (AES and ChaCha20 were recently in use, but these may change again at any time). But the name stuck around, so that existing software would benefit from better algorithms (by definition, no software could have been dependent on the old algorithm, as it was random).

This. You basically shouldn't ever use arc4random directly in Swift, except in quite specific circumstances (this is a "if you have to use it, you'll know" kinda thing).


Just in case anyone ends up here in the future because they search for "arc4random uniform distribution" or something, note that the correct way to write this and get an unbiased generator in non-Swift languages like C is:

1 + arc4random_uniform(6)
9 Likes
Terms of Service

Privacy Policy

Cookie Policy