0

So I am using this code to generate a random integer from 1 to 13. This is the code that gets executed, when pressing my UIButton:

currentValue = Int.random(in: 1 ... 13)

This generates a random value, but how can I avoid getting the same number two times in a row?

  • By "two times in a row" do you mean that a number can come up more than once, just never consecutively, or the same number shouldn't show up ever again? – Tor Jul 01 '19 at 23:55
  • @Tor Sorry; The same number can show up another time, but never consecutively. Sorry for by bad English. – Kurt Nobel Jul 01 '19 at 23:56
  • Well you can't. Otherwise it wouldn't be random. If you want to apply additional rules to a random function, you will need to write your own 'random' function. If this is the only rule, then you can (a) remember each return value by storing to a variable as `lastRandom`, then use a while loop to generate the next random number until the answer does not equal `lastRandom`. – Chris Shaw Jul 01 '19 at 23:57
  • I just created an [`Int.random(in:excluding:)`](https://stackoverflow.com/a/27548748/1630618) – vacawama Jul 02 '19 at 01:03

1 Answers1

1

Well you can't. Otherwise it wouldn't be random. If you want to apply additional rules to a random function, you will need to write your own 'random' function. If this is the only rule, then you can (a) remember each return value by storing to a variable as lastRandom, then use a while loop to generate the next random number until the answer does not equal lastRandom.

var lastRandom: Int = -1
func KurtsRandom() -> Int
{
  var result = lastRandom
  while result == lastRandom
  {
    result = Int.random(in: 1 ... 13)
  }

  lastRandom = result

  return result
}
Chris Shaw
  • 1,610
  • 2
  • 10
  • 14