0

with this code arc4random makes appear a random number between 0 and 3 but it usually make appear the same number in a row, so, how i make arc4random not display the same number in a row? ( for example: 1-3 not 1-1 or 2-2)

func setRandomPosition() {

    let i = arc4random_uniform(4)

    createRandomXY()

    if i == 0 {
        self.rect.center.x = self.topXRandomPosition
        self.rect.center.y = self.topYRandomPosition
    } else if i == 1 {
        self.rect.center.x = self.bottomXRandomPosition
        self.rect.center.y = self.bottomYRandomPosition
    } else if i == 2 {
        self.rect.center.x = self.rightXRandomPosition
        self.rect.center.y = self.rightYRandomPosition
    } else if i == 3 {
        self.rect.center.x = self.leftXRandomPosition
        self.rect.center.y = self.leftYRandomPosition
    }
}
David Dume
  • 65
  • 1
  • 1
  • 8
  • Duplicate with the proviso that a little more work would be needed because there are three possible non-duplicates – Bill Woodger Jan 19 '16 at 15:04
  • I would recommend [shuffling](http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift) a collection of possibilities (0-3) and store that in an instance variable. When `setRandomPosition` is called return and remove and item from the array. If the array is empty add all values back and shuffle again. The other option If you just want to avoid one duplicate then store the last value, while the new random number equals the last value generate a new one. – Joe Jan 19 '16 at 15:26
  • Given that north posters are only asking how to insure that the next number is not the same as the last number, no proviso is necessary, it's an exact duplicate. If this poster is attempting to find out how to insure there are no duplates, i.e. Each number 0-3 will be used before any repeats, then he needs to rewrite the question. – David Berry Jan 19 '16 at 15:26
  • It's also a duplicate if he's trying to do a shuffle, see this question http://stackoverflow.com/questions/29317851/generate-random-questions-in-swift – David Berry Jan 19 '16 at 15:30

0 Answers0