Shortest Code to Create an Array of Random Numbers in Swift

Create an array of random numbers in Swift

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) }
}

Edit/update: Swift 5.1 or later

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

extension RangeExpression where Bound: FixedWidthInteger {
func randomElements(_ n: Int) -> [Bound] {
precondition(n > 0)
switch self {
case let range as Range<Bound>: return (0..<n).map { _ in .random(in: range) }
case let range as ClosedRange<Bound>: return (0..<n).map { _ in .random(in: range) }
default: return []
}
}
}

extension Range where Bound: FixedWidthInteger {
var randomElement: Bound { .random(in: self) }
}

extension ClosedRange where Bound: FixedWidthInteger {
var randomElement: Bound { .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.

Generate a Swift array of nonrepeating random numbers

If you use your method the problem is, that you will create a new random-number each time. So you possibly could have the same random-number 4 times and so your array will only have one element.

So, if you just want to have an array of numbers from within a specific range of numbers (for example 0-100), in a random order, you can first fill an array with numbers in 'normal' order. For example with for loop etc:

var min = 1
var max = 5
for var i = min; i<= max; i++ {
temp.append(i)
}

After that, you can use a shuffle method to shuffle all elements of the array with the shuffle method from this answer:

func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C {
let count = countElements(list)
for i in 0..<(count - 1) {
let j = Int(arc4random_uniform(UInt32(count - i))) + i
swap(&list[i], &list[j])
}
return list
}

Ater that you can do something like that:

shuffle(temp)        // e.g., [3, 1, 2, 4, 5]

Generate Array of Unique Random Numbers within Inclusive Range

You could make your live much easier using a Set to store all random numbers until you reach the expected number of randoms:

func uniqueRandoms(numberOfRandoms: Int, minNum: Int, maxNum: UInt32) -> [Int] {
var uniqueNumbers = Set<Int>()
while uniqueNumbers.count < numberOfRandoms {
uniqueNumbers.insert(Int(arc4random_uniform(maxNum + 1)) + minNum)
}
return uniqueNumbers.shuffled()
}

print(uniqueRandoms(numberOfRandoms: 5, minNum: 0, maxNum: 10))

func uniqueRandoms(numberOfRandoms: Int, minNum: Int, maxNum: UInt32, blackList: Int?) -> [Int] {
var uniqueNumbers = Set<Int>()
while uniqueNumbers.count < numberOfRandoms {
uniqueNumbers.insert(Int(arc4random_uniform(maxNum + 1)) + minNum)
}
if let blackList = blackList {
if uniqueNumbers.contains(blackList) {
while uniqueNumbers.count < numberOfRandoms+1 {
uniqueNumbers.insert(Int(arc4random_uniform(maxNum + 1)) + minNum)
}
uniqueNumbers.remove(blackList)
}
}
return uniqueNumbers.shuffled()
}

uniqueRandoms(numberOfRandoms: 3, minNum: 0, maxNum: 10, blackList: 8) // [0, 10, 7]

How to generate a random number in Swift?

Swift 4.2+

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types.
You can call the random() method on numeric types.

let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()

Pick a random element from an array

Swift 4.2 and above

The new recommended approach is a built-in method on the Collection protocol: randomElement(). It returns an optional to avoid the empty case I assumed against previously.

let array = ["Frodo", "Samwise", "Merry", "Pippin"]
print(array.randomElement()!) // Using ! knowing I have array.count > 0

If you don't create the array and aren't guaranteed count > 0, you should do something like:

if let randomElement = array.randomElement() { 
print(randomElement)
}

Swift 4.1 and below

Just to answer your question, you can do this to achieve random array selection:

let array = ["Frodo", "Samwise", "Merry", "Pippin"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

The castings are ugly, but I believe they're required unless someone else has another way.

Is there a way to instantly generate an array filled with a range of values in Swift?

You can create an array with a range like this:

var values = Array(0...100)

This give you an array of [0, ..., 100]

Random number from an array without repeating the same number twice in a row?

The code below doesn't random the same number.

   var currentNo: UInt32 = 0

func randomNumber(maximum: UInt32) -> Int {

var randomNumber: UInt32

do {
randomNumber = (arc4random_uniform(maximum))
}while currentNo == randomNumber

currentNo = randomNumber

return Int(randomNumber)
}

How to randomly generate numbers that don't repeat?

How does one generate a random number in Apple's Swift language?

check this answer, you can then write an easy function to check your array or data structure for duplicate numbers.



Related Topics



Leave a reply



Submit