PoisonedApps PoisonedApps - 1 year ago 44
Swift Question

Random number from an array without repeating the same number twice in a row?

I am making a game using Swift and SpriteKit where i move an object to random locations based on an array.

The array that is made up of CGPoints:

let easyArray = [CGPointMake(0,0), CGPointMake(126.6,0), CGPointMake(253.4,0), CGPointMake(0,197.5), CGPointMake(126.7,197.5), CGPointMake(253.4,197.5), CGPointMake(0,395), CGPointMake(126.7,395), CGPointMake(253.4,395)]

I use this function to generate a random number:

func randomNumber(maximum: UInt32) -> Int {

var randomNumber = arc4random_uniform(maximum)
while previousNumber == randomNumber {
randomNumber = arc4random_uniform(maximum)
previousNumber = randomNumber
return Int(randomNumber)

I used this to move the object based on the random number generated:

let greenEasy = randomNumberNew(9)
let moveSelector = SKAction.moveTo(easyArray[greenEasy], duration: 0)

I have done some reading online and found that the "While" condition should make it so that the same random number isn't generate twice in a row. But it still happens.

Can anyone please help me on how to make it so i don't get the same number twice in a row?

Answer Source

The code below doesn't random the same number.

   var currentNo: UInt32 = 0

    func randomNumber(maximum: UInt32) -> Int {

        var randomNumber: UInt32

        do {
            randomNumber = (arc4random_uniform(maximum))
        }while currentNo == randomNumber

        currentNo = randomNumber

        return Int(randomNumber)