How to generate a random number in Swift without repeating the previous random number?
Solution 1:
my solution, i think its easy to understand
var nums = [0,1,2,3,4,5,6,7,8,9]
while nums.count > 0 {
// random key from array
let arrayKey = Int(arc4random_uniform(UInt32(nums.count)))
// your random number
let randNum = nums[arrayKey]
// make sure the number isnt repeated
nums.swapAt(arrayKey, nums.count-1)
nums.removeLast()
}
Solution 2:
Store the previous generated number in a variable and compare the generated number to the previous number. If they match generate a new random number. Repeat the generation of new numbers until they don't match.
var previousNumber: UInt32? // used in randomNumber()
func randomNumber() -> UInt32 {
var randomNumber = arc4random_uniform(10)
while previousNumber == randomNumber {
randomNumber = arc4random_uniform(10)
}
previousNumber = randomNumber
return randomNumber
}