create array of random numbers in swift

倖福魔咒の 提交于 2020-02-01 04:58:28

问题


I'm just starting to learn swift. I'm attempting to create an array of several random numbers, and eventually sort the array. I'm able to create an array of one random number, but what's the best way to iterate this to create an array of several random numbers?

func makeList() {
   var randomNums = arc4random_uniform(20) + 1

    let numList = Array(arrayLiteral: randomNums)

}

makeList()

Any help is greatly appreciated.


回答1:


Edit/update: Swift 4.2 or later

In Swift 4.2 there is a new static method for fixed width integers that makes the syntax more user friendly:

func makeList(_ n: Int) -> [Int] {
    return (0..<n).map { _ in .random(in: 1...20) }
}

We can also extend Range and ClosedRange and create a method to return n random elements:

extension Range where Bound: FixedWidthInteger {
    func randomElements(_ n: Int) -> [Bound] {
        guard n > 0 else { return [] }
        return (0..<n).map { _ in .random(in: self) }
    }
    var randomElement: Bound { return .random(in: self) }
}

extension ClosedRange where Bound: FixedWidthInteger {
    func randomElements(_ n: Int) -> [Bound] {
        guard n > 0 else { return [] }
        return (0..<n).map { _ in .random(in: self) }
    }
    var randomElement: Bound { return .random(in: self) }
}

Usage:

let randomElements = (1...20).randomElements(5)  // [17, 16, 2, 15, 12]
randomElements.sorted() // [2, 12, 15, 16, 17]

let randomElement = (1...20).randomElement   // 4 (note that the computed property returns a non-optional instead of the default method which returns an optional)

let randomElements = (0..<2).randomElements(5)  // [1, 0, 1, 1, 1]
let randomElement = (0..<2).randomElement   // 0

Note: for Swift 3, 4 and 4.1 and earlier click here.




回答2:


Ok, this is copy/paste of a question asked elsewhere, but I think I'll try to remember that one-liner :

var randomArray = map(1...100){_ in arc4random()}

(I love it !)

EDIT

If you need a random number with an upperBound (exclusive), use arc4random_uniform(upperBound)

e.g. : random number between 0 & 99 : arc4random_uniform(100)

Swift 2 update

var randomArray = (1...100).map{_ in arc4random()}



回答3:


Swift 4.2 or later

func makeList(_ n: Int) -> [Int] {
    return (0..<n).map{ _ in Int.random(in: 1 ... 20) }
}

let list = makeList(5)  //[11, 17, 20, 8, 3]
list.sorted() // [3, 8, 11, 17, 20]



回答4:


Swift 5

This creates an array of size 5, and whose elements range from 1 to 10 inclusive.

let arr = (1...5).map( {_ in Int.random(in: 1...10)} )



回答5:


How about this? Works in Swift 5 and Swift 4.2:

public extension Array where Element == Int {
    static func generateRandom(size: Int) -> [Int] {
        guard size > 0 else {
            return [Int]()
        }
        return Array(0..<size).shuffled()
    }
}

Usage:

let array = Array.generateRandom(size: 10)
print(array)

Prints e.g.:

[7, 6, 8, 4, 0, 3, 9, 2, 1, 5]

The above approach gives you unique numbers. However, if you need redundant values, use the following implementation:

public extension Array where Element == Int {
    static func generateRandom(size: Int) -> [Int] {
        guard size > 0 else {
            return [Int]()
        }
        var result = Array(repeating: 0, count: size)
        for index in 0..<result.count {
            result[index] = Int.random(in: 0..<size)
        }
        return result
    }
}

A shorter version of the above using map():

public extension Array where Element == Int {
    static func generateRandom(size: Int) -> [Int] {
        guard size > 0 else {
            return [Int]()
        }
        var result = Array(repeating: 0, count: size)
        return result.map{_ in Int.random(in: 0..<size)}
    }
}


来源:https://stackoverflow.com/questions/28140145/create-array-of-random-numbers-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!