在Swift中生成一个范围内的随机整数的最简单方法是什么?

Ron*_*onH 21 random limits range swift

我到目前为止设计的方法是这样的:

func randRange (lower : Int , upper : Int) -> Int {
    let difference = upper - lower
    return Int(Float(rand())/Float(RAND_MAX) * Float(difference + 1)) + lower
}
Run Code Online (Sandbox Code Playgroud)

这会生成低位和高位之间的随机整数.

Jea*_*nan 51

这是一个稍微轻松的版本:

func randRange (lower: Int , upper: Int) -> Int {
    return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
Run Code Online (Sandbox Code Playgroud)

如果您确定此函数仅适用于无符号值,则可以进一步简化:

func randRange (lower: UInt32 , upper: UInt32) -> UInt32 {
    return lower + arc4random_uniform(upper - lower + 1)
}
Run Code Online (Sandbox Code Playgroud)

或者,按照Anton的(给你+1),使用范围作为参数的绝佳主意:

func random(range: Range<UInt32>) -> UInt32 {
    return range.startIndex + arc4random_uniform(range.endIndex - range.startIndex + 1)
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*kov 14

根据评论中的建议编辑删除模偏差.(谢谢!)

我认为这样做的一种巧妙方法可能是使用Swift的Range来定义边界,因为那时你可以指定1..100或1 ... 100(包括或排除上限).我到目前为止所提出的最好的是:

import Foundation // needed for rand()

func randInRange(range: Range<Int>) -> Int {
    // arc4random_uniform(_: UInt32) returns UInt32, so it needs explicit type conversion to Int
    // note that the random number is unsigned so we don't have to worry that the modulo
    // operation can have a negative output
    return  Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex
}

// generate 10 random numbers between -1000 and 999
for _ in 0...100 {
    randInRange(-1000...1000)
}
Run Code Online (Sandbox Code Playgroud)

我尝试在Range上使用扩展,但你似乎无法扩展Range <T where T:Int>.如果你能得到像(1..100).rand()这样的语法会更好.

  • [Modulo bias](http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator)是一个众所周知的结果:在大多数情况下,使用模运算会产生不均匀的结果. (2认同)

Bil*_*eem 6

这可以在最新的 Swift 版本中完成:

Int.random(in: 1...99)
Run Code Online (Sandbox Code Playgroud)

上面将生成一个 1 到 99 之间(包括 99)的随机整数。