I'd like to generate multiple different random numbers in Swift. Here is the procedure.
- Set up an empty array
- Generate a random number
Check if the array is empty
a. If the array is empty, insert the random number
b. If the array is not empty, compare the random number to the numbers in array
i. If the numbers are the same, repeat 2
ii. if the numbers are not the same, insert the random number and repeat 2import UIKit //the random number generator func randomInt(min: Int, max:Int) -> Int { return min + Int(arc4random_uniform(UInt32(max - min + 1))) } var temp = [Int]() for var i = 0; i<4; i++ { var randomNumber = randomInt(1, 5) if temp.isEmpty{ temp.append(randomNumber) } else { //I don't know how to continue... } }
Below is my suggestion. I like this way since it is short and simple :)
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:
After that, you can use a shuffle method to shuffle all elements of the array with the shuffle method from this answer:
Ater that you can do something like that:
The construct you’re looking for with your approach might be something like:
This will be fine for tiny ranges like yours, but for larger ranges it will be very slow, because for the last few numbers you are waiting for the random number to hit precisely the remaining handful of possibilities. I just tried generating from a range of 200 in a playground and it took 9 seconds.
If you want a random selection of numbers with guaranteed coverage over a range, you could generate it like by taking that range and shuffling it, like this:
If you want a selection of n non-repeating random numbers from a range
0..<m
, there’s a particularly pretty algorithm to do this that generates an ascending sequence of random numbers from that range:Which you could use like so: