How to create a random number in Swift without repeating the previous random number?

I am new to Swift and to programming logic in general, so bear with me

How can you generate a random number from 0 to 9 in Swift without repeating the last generated number? As in the same issue will not fit twice in a row.

+11
source share
5 answers

Save the previous generated number in a variable and compare the generated number with the previous number. If they correspond to the generation of a new random number. Repeat the generation of new numbers until they 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
}
+11
source

my decision, I think it’s 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.removeAtIndex(arrayKey)
}
+17
source

Swift 5

, , .

10 , 9 ( 0 9, ). 1, 9 , . , , .

Int.random(in:excluding:) , exclude.

extension Int {
    static func random(in range: ClosedRange<Int>, excluding x: Int) -> Int {
        if range.contains(x) {
            let r = Int.random(in: Range(uncheckedBounds: (range.lowerBound, range.upperBound)))
            return r == x ? range.upperBound : r
        } else {
            return Int.random(in: range)
        }
    }
}

:

// Generate 30 numbers in the range 1...3 without repeating the
// previous number  
var r = Int.random(in: 1...3)
for _ in 1...30 {
    r = Int.random(in: 1...3, excluding: r)
    print(r, terminator: " ")
}
print()

1 3 2 1 2 1 3 2 1 3 1 3 2 3 1 2 3 2 1 3 2 1 3 1 2 3 2 1 2 1 3 2 3 2 1 3 1 2 1 2


:

var previousNumber = arc4random_uniform(10)   // seed the previous number

func randomNumber() -> UInt32 {
    var randomNumber = arc4random_uniform(9)  // generate 0...8
    if randomNumber == previousNumber {
        randomNumber = 9
    }
    previousNumber = randomNumber
    return randomNumber
}
+4

- /:

let current = ...
var next: Int

repeat {
    next = Int(arc4random_uniform(9))
} while current == next

// Use `next`
+2

, , arc4random_uniform (SIZEOFARRAY) , , .

0

Source: https://habr.com/ru/post/1608921/


All Articles