Swift rand() not being random

2019-02-24 04:00发布

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!

标签: random swift
3条回答
再贱就再见
2楼-- · 2019-02-24 04:19

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-24 04:21

Using rand() is fine, you can seed the pseudo-random number generator with this call at the beginning of your program:

srand(UInt32(time(nil)))
查看更多
SAY GOODBYE
4楼-- · 2019-02-24 04:26

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.

查看更多
登录 后发表回答