5

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.

timbo
  • 13,244
  • 8
  • 51
  • 71
slooker
  • 153
  • 1
  • 1
  • 10
  • I looked at the other comments, and they were actually just copying and pasting what was in the book. – slooker Jun 04 '14 at 00:42
  • look at the answers in the other question. they are a lot simpler than this and don't require a seed – Connor Pearson Jun 04 '14 at 00:44
  • Yup. I'm deleting this question since it was duplicated. arc4random() is much simpler. Sorry! -- edit, can't delete because there are answers. Oh well. – slooker Jun 04 '14 at 00:45

2 Answers2

5

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.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
0

Pseudorandom number generators need a "seed" value. In your case, if you change lastRandom with any number, you'll get a different sequence.

zneak
  • 134,922
  • 42
  • 253
  • 328