Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate a random number in swift? [duplicate]

Tags:

random

swift

tl:dr; How do I generate a random number, because the method in the book picks the same numbers every time.

This seems to be the way in Swift to generate a random number, based on the book released from Apple.

protocol RandomNumberGenerator {
    func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0
    func random() -> Double {
        lastRandom = ((lastRandom * a + c) % m)
        return lastRandom / m
    }
}
let generator = LinearCongruentialGenerator()

for _ in 1..10 {
    // Generate "random" number from 1-10
    println(Int(generator.random() * 10)+1)
}

The problem is that in that for loop I put at the bottom, the output looks like this:

4
8
7
8
6
2
6
4
1

The output is the same every time, no matter how many times I run it.

like image 698
slooker Avatar asked Jun 04 '14 00:06

slooker


1 Answers

The random number generator you created is not truly random, it's psueodorandom.

With a psuedorandom random number generator, the sequence depends on the seed. Change the seed, you change the sequence.

One common usage is to set the seed as the current time, which usually makes it random enough.

You can also use the standard libraries: arc4random(). Don't forget to import Foundation.

like image 108
Anubian Noob Avatar answered Oct 12 '22 12:10

Anubian Noob