Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift rand() not being random

Tags:

random

swift

Today is my first day with Swift, and I have run into a problem. I am using rand to generate a random number, but it is giving me the same results every time I run the code.

main.swift:

import Foundation

var player = Player()

for _ in 1..6 {
    println(player.kick())
}

player.swift:

import Foundation

class Player {
    var health = 25
    var xp = 15
    var upgrades = ["kick": 0, "punch": 0]

    func kick() -> Int {
        let range = (3, 7)
        let damage = Int(rand()) % (range.1 - range.0) + range.0 + 1
        return damage
    }

    func punch() -> Int {
        let range = (4, 6)
        let damage = Int(rand()) % (range.1 - range.0) + range.0 + 1
        return damage
    }
}

Every time I run the code, it logs these numbers:

7
5
5
6
6

I also tried this: Int(arc4random(range.1 - range.0)) + range.0 + 1 but it said it couldn't find an overload for + that accepts the supplied arguments

I have no idea why this would be happening. I'd appreciate some help, thanks!

like image 257
Addison Avatar asked Dec 02 '22 19:12

Addison


2 Answers

You should never use rand(), use arc4random - it's a much better generator. If you check its man-pages, you'll find that it has an integer range generator form called arc4random_uniform(), which you should use to avoid modulo bias when the modulus is not a power of 2. I believe the following is what you want, it worked for me in playground:

let damage = arc4random_uniform(UInt32(range.1 - range.0) + 1) + UInt32(range.0)

The + 1 is because the upper end of arc4random_uniform() is non-inclusive. If your range is (4,7), this should give occurrences of 4, 5, 6, and 7.

like image 148
pjs Avatar answered Jan 08 '23 21:01

pjs


rand() in most programming environments gives you a repeatable sequence of pseudo-random numbers, by design. Look for a function called seed or srand for ways to initialize the random number generator.

like image 20
Russell Borogove Avatar answered Jan 08 '23 20:01

Russell Borogove