0

I'm trying to make it so when I click a button it generates a random int between 1 and 13 (inclusive), it doesn't give the same number twice in a row. Fairly new to swift btw

Ive looked at many other topics on here and still can't get it to work.

random int function:

func randomIntBetween(low:Int, high:Int) -> Int {
  let range = high - (low - 1)
  return (Int(arc4random()) % range) + (low - 1)
}

and the button:

    @IBAction func higher(sender: AnyObject) {
    //Random Number between 1-13
    numberLabel.text = String(randomIntBetween(2, high: 14))
    print(numberLabel.text)

Thanks

Jeremy
  • 434
  • 1
  • 4
  • 17

1 Answers1

0

Create a variable that stores the last used Int and if that matches the new random recall the function.

var lastUsedRandom: Int = 0

func randomIntBetween(low:Int, high:Int) -> Int {
    let range = high - (low - 1)
    let newRandom = (Int(arc4random()) % range) + (low - 1)
    if newRandom == lastUsedRandom{
        randomIntBetween(low, high: high)
    }else{
        lastUsedRandom = newRandom
        return newRandom
    }
}
heckj
  • 7,136
  • 3
  • 39
  • 50
TheValyreanGroup
  • 3,554
  • 2
  • 12
  • 30