如何在arc4random_uniform()的范围之间创建随机数?

时间:2014-06-10 03:32:51

标签: range swift arc4random

所以我在这个代码中的目标是随机滚动两个骰子,因为我们都知道你的常规骰子只有6个边,所以我导入了Foundation来访问arc4random_uniform(UInt32)。我试图使用(1..7)的范围来避免随机获得0,但是返回了一个我不太喜欢的错误。我试着这样做:

dice1 = arc4random_uniform(UInt32(1..7))
然而,

返回了

  

找不到接受所提供参数的'init'的重载

我希望这对你有足够的信息来帮助我:)

请注意我只是在操场上练习快速练习。我不必学习如何做到这一点;在我开始构建实际的应用程序之前,我只是在修补:D

//imports random number function
import Foundation
//creates data storage for dice roll
var dice1: UInt32 = 0
var dice2: UInt32 = 0
//counter variable
var i = 0
//how many times snake eyes happens
var snakeeyes = 0
 //how many times a double is rolled
var `double` = 0
//rolls dice 100 times
while i < 100{
    //from here
    //sets dice roll

这会返回错误“Range $ T3”无法转换为UInt32

   dice1 = arc4random_uniform(1..7)
   dice2 = arc4random_uniform(1..7)
    //checks for snake eyes
    if dice1 == 1 && dice2 == 1 {
        snakeeyes = snakeeyes + 1

    }
    //checks for doubles
    if dice1 == dice2{
        `double` = `double` + 1
    }
    //increases counter
        i = i + 1
    //to here
}
println("You got Snake Eyes \(snakeeyes) times.")
println("You got Doubles, \(`double`) times.")

18 个答案:

答案 0 :(得分:253)

我相信你应该做

dice1 = arc4random_uniform(6) + 1;

获得范围1 - 6.虽然我没有iOS目标C,也没有任何关于swift语言的知识。随机方法应该返回0到5之间的值,+ 1将使它成为1到6之间的值。

如果您需要介于10 - 30之间的范围,那么只需执行

int random = arc4random_uniform(21) + 10;

答案 1 :(得分:91)

我做了一个Int类型扩展。在操场上测试它,希望这是有用的。它也接受负范围:

extension Int
{
    static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.startIndex < 0   // allow negative ranges
        {
            offset = abs(range.startIndex)
        }

        let mini = UInt32(range.startIndex + offset)
        let maxi = UInt32(range.endIndex   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}

使用

var aRandomInt = Int.random(-500...100)  // returns a random number within the given range.

或将其定义为Range扩展名,如下所示:

extension Range
{
    var randomInt: Int
    {
        get
        {
            var offset = 0

            if (startIndex as Int) < 0   // allow negative ranges
            {
                offset = abs(startIndex as Int)
            }

            let mini = UInt32(startIndex as Int + offset)
            let maxi = UInt32(endIndex   as Int + offset)

            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt

答案 2 :(得分:60)

相当多的好答案,但我只想分享我个人最喜欢的Swift随机数生成函数的正整数:

Swift 2

func randomNumber(range: Range<Int> = 1...6) -> Int {
    let min = range.startIndex
    let max = range.endIndex
    return Int(arc4random_uniform(UInt32(max - min))) + min
}

Swift 3

这是Swift 3的快速更新,作为奖励,它现在适用于符合SignedInteger协议的任何值类型 - 对于需要指定Int16,Int32等的核心数据应用程序来说更加方便。快速说明,如果你真的需要它来处理无符号整数,只需复制整个函数,然后将SignedInteger替换为UnsignedInteger,将toIntMax()替换为toUIntMax()

func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
    let length = (range.upperBound - range.lowerBound + 1).toIntMax()
    let value = arc4random().toIntMax() % length + range.lowerBound.toIntMax()
    return T(value)
}

Swift 4

由于在Swift 4中删除了toIntMax(),我们现在必须使用不同的方法转换为常见的整数类型。在这个例子中,我使用的Int64足够大,但是如果你使用无符号整数或者有Int128或Int256自定义类型,你应该使用它们。

public func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
    let length = Int64(range.upperBound - range.lowerBound + 1)
    let value = Int64(arc4random()) % length + Int64(range.lowerBound)
    return T(value)
}

另外,对于总random-phile,这是一个从任何Collection类型对象返回随机元素的扩展。请注意,这使用上面的函数来生成索引,因此您需要两者。

extension Collection {
    func randomItem() -> Self.Iterator.Element {
        let count = distance(from: startIndex, to: endIndex)
        let roll = randomNumber(inRange: 0...count-1)
        return self[index(startIndex, offsetBy: roll)]
    }
}

用法

randomNumber()

返回1到6之间的随机数。

randomNumber(50...100)

返回50到100之间的数字。当然,你可以用任何你喜欢的值替换50和100的值。

Swift 4.2

唉,我最好的StackOverflow答案终于被淘汰了。您现在可以使用Int.random(in: 1 ... 6)生成给定范围内的随机数。也适用于其他形式的整数和浮点数。集合类型现在还提供shuffle()randomElement()功能。因此,除非您想使用特定的随机函数类型,否则不再需要花哨的随机函数。

答案 3 :(得分:19)

根据Swift 4.2,现在很容易获得像这样的随机数

let randomDouble = Double.random(in: -7.9...12.8)

let randomIntFrom0To10 = Int.random(in: 0 ..< 10)

for more details check this out

答案 4 :(得分:17)

如果你想为随机数创建。这是数字Int和Double的扩展名,Float

/**
    Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, UInt(sizeof(T)))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (#lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(upper - lower + 1))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(#lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(#lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

使用

let randomNumDouble = Double.random(lower: 0.00, upper: 23.50)
let randomNumInt = Int.random(lower: 56, upper: 992)
let randomNumInt =Float.random(lower: 6.98, upper: 923.09)

答案 5 :(得分:13)

Swift 3/4:

func randomNumber(range: ClosedRange<Int> = 1...6) -> Int {
    let min = range.lowerBound
    let max = range.upperBound
    return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

答案 6 :(得分:8)

那是因为arc4random_uniform()定义如下:

func arc4random_uniform(_: UInt32) -> UInt32

它需要一个UInt32作为输入,并吐出一个UInt32。您试图将一系列值传递给它。 arc4random_uniform为您提供0和之间的随机数和您传递的数字(仅限于),因此,例如,如果您想要找到介于-50和50之间的随机数,就像在[-50, 50]中一样,您可以使用{{ 1}}

答案 7 :(得分:5)

夫特:

var index = 1 + random() % 6

答案 8 :(得分:5)

我修改了@DaRk -_- D0G使用Swift 2.0的答案

/**
Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
    var r: T = 0
    arc4random_buf(&r, sizeof(T))
    return r
}
public extension Int {
    /**
    Create a random num Int
    :param: lower number Int
    :param: upper number Int
    :return: random number Int
    By DaRkDOG
    */
    public static func random (lower: Int , upper: Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }

}
public extension Double {
    /**
    Create a random num Double
    :param: lower number Double
    :param: upper number Double
    :return: random number Double
    By DaRkDOG
    */
    public static func random(lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
}
public extension Float {
    /**
    Create a random num Float
    :param: lower number Float
    :param: upper number Float
    :return: random number Float
    By DaRkDOG
    */
    public static func random(lower: Float, upper: Float) -> Float {
        let r = Float(arc4random(UInt32)) / Float(UInt32.max)
        return (r * (upper - lower)) + lower
    }
}

答案 9 :(得分:3)

快速......

这是包容性的,调用random(1,2)将返回1或2,这也适用于负数。

    func random(min: Int, _ max: Int) -> Int {
        guard min < max else {return min}
        return Int(arc4random_uniform(UInt32(1 + max - min))) + min
    }

答案 10 :(得分:3)

答案只是一行代码:

let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number

替代解决方案是:

    func generateRandomNumber(numDigits: Int) -> Int{
    var place = 1
    var finalNumber = 0;
    var finanum = 0;
    for var i in 0 ..< numDigits {
        place *= 10
        let randomNumber = arc4random_uniform(10)         
        finalNumber += Int(randomNumber) * place
        finanum = finalNumber / 10
           i += 1
    }
    return finanum
}

虽然缺点是数字不能从0开始。

答案 11 :(得分:1)

从Swift 4.2开始:

Int {    
    public static func random(in range: ClosedRange<Int>) -> Int
    public static func random(in range: Range<Int>) -> Int
}

使用方式:

Int.random(in: 2...10)

答案 12 :(得分:1)

编辑:Swift 4.2+现在提供此功能:

(100...200).randomElement()

扩展Range

对我来说是不合时宜的
public extension Range where Bound == Int {
    var random: Int {
        return lowerBound + Int(arc4random_uniform(UInt32(upperBound - lowerBound)))
    }
}

public extension ClosedRange where Bound == Int {
    var random: Int {
        return lowerBound + Int(arc4random_uniform(UInt32(upperBound - lowerBound + 1)))
    }
}

使用中:

let foo = (100..<600).random

答案 13 :(得分:1)

我使用以下代码成功完成了创建随机数:

var coin = arc4random_uniform(2) + 1

希望这可以帮到你。

答案 14 :(得分:0)

var rangeFromLimits = arc4random_uniform((UPPerBound - LOWerBound)+ 1))+ LOWerBound;

答案 15 :(得分:0)

希望这是有效的。在arc4random_uniform()?

的范围之间设置随机数
var randomNumber = Int(arc4random_uniform(6))
print(randomNumber)

答案 16 :(得分:0)

使用 Swift 4 / Xcode 9 + 时,可能会发现Ted van Gaalen的答案有点更新Range扩展版本有用了:

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        get {
            var offset = 0
            if lowerBound < 0 {
                offset = abs(lowerBound)
            }
            let mini = UInt32(lowerBound + offset)
            let maxi = UInt32(upperBound + offset)
            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
}

let n = (-1000 ... 1000).randomFromRange
print(n)

或者这是一个支持开放和封闭间隔的“hacky”解决方案:

extension CountableRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound)
    }
}

extension CountableClosedRange where Bound == Int {
    var randomFromRange: Bound {
        return uniformRandom(from: lowerBound, to: upperBound - 1)
    }
}

func uniformRandom(from: Int, to: Int) -> Int {
    var offset = 0
    if from < 0 {
        offset = abs(from)
    }
    let mini = UInt32(from + offset)
    let maxi = UInt32(to + offset)
    return Int(mini + arc4random_uniform(maxi - mini)) - offset
}

不确定是否有办法同时为两种类型的间隔添加属性。

答案 17 :(得分:0)

Swift 3 Xcode Beta 5解决方案。 基于Ted van Gaalen答案。

extension Int
  {
     static func random(range: Range<Int> ) -> Int
    {
        var offset = 0

        if range.lowerBound < 0   // allow negative ranges
        {
            offset = Swift.abs(range.lowerBound)
        }

        let mini = UInt32(range.lowerBound + offset)
        let maxi = UInt32(range.upperBound   + offset)

        return Int(mini + arc4random_uniform(maxi - mini)) - offset
    }
}