How to make sure the generated random number is not equal to the next generated number?

2 Solutions Collect From Internet About “How to make sure the generated random number is not equal to the next generated number?”

You need to make randomNumber a property of your ViewController so that it is remembered between button presses. Each time, there are only 2 valid random numbers, so generate a number in the range 0 to 1 and then change it to 2 if it matches your previous number:

class ViewController: UIViewController {
    // Give randomNumber an initial value
    var randomNumber = Int(arc4random_uniform(UInt32(3)))

    @IBAction func buttonPressed(button: UIButton) {
        let currentNumber = randomNumber
        randomNumber = Int(arc4random_uniform(UInt32(2)))
        if currentNumber == randomNumber {
            randomNumber = 2
        }
    }
}

This has the advantage of only needing 1 random number each button press.

Note that if you prevent the same number from appearing twice in a row, your sequence is no longer random / pseudorandom. However, if you must, you can compare the newest value to the previous and retry until they differ.