# 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:

• Sort array by order of values in other array
• How to get list of common elements of 2 array in swift
• Swift: sort array with alternative comparison
• Find unique values in a Swift Array
• Shift Swift Array
• Simple persistent storage in Swift
• ``````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)
selector.runAction(moveSelector)
``````

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?

### 4 Solutions Collect From Internet About “Random number from an array without repeating the same number twice in a row?”

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)
}
``````

I think Larme’s suggestion is pretty clever, actually.

``````easyArray.append(easyArray.removeAtIndex(Int(arc4random_uniform(UInt32(easyArray.count)-1))))
selector.runAction(SKAction.moveTo(easyArray.last!, duration: 0))
``````

I would recommend to not use while() loops with randomizers.

Theoretically it can cause infinite loops in worst case scenario, in more positive scenario it will just take few loops before you get desired results.

Instead I would advice to make an NSArray of all values, remove from this NSArray last randomized element and randomize any of other existing elements from such an array – that is guarantee result after only one randomize iteration.

It can be easily achieved by making NSArray category in Objective-C:

``````- (id) randomARC4Element
{
if(self.count > 0)
{
return [self objectAtIndex:[self randomIntBetweenMin:0 andMax:self.count-1]];
}

return nil;
}

- (int)randomIntBetweenMin:(int)minValue andMax:(int)maxValue
{
return (int)(minValue + [self randomFloat] * (maxValue - minValue));
}

- (float)randomFloat
{
return (float) arc4random() / UINT_MAX;
}
``````

If you can use linq then you can select a random value that doesn’t match the last value. Then for any left over values you can loop through and find valid places to insert them.

It’s not the most efficient but it works.

``````public static List<int> Randomize(List<int> reps, int lastId) {
var rand = new Random();

var newReps = new List<int>();
var tempReps = new List<int>();
while (tempReps.Any(x => x != lastId)) {
var validReps = tempReps.FindAll(x => x != lastId);
var i = rand.Next(0, validReps.Count - 1);
lastId = validReps[i];
tempReps.Remove(validReps[i]);
}
while (tempReps.Any()) {
var tempRep = tempReps.First();
bool placed = false;
for (int i = 0; i < newReps.Count; i++) {
if (newReps[i] == tempRep) {
continue;
}
else if ((i < newReps.Count - 1) && (newReps[i + 1] == tempRep)) {
continue;
}
else {
newReps.Insert(i + 1, tempRep);
placed = true;
break;
}
}

if (placed) {
tempReps.Remove(tempRep);
}
else {
throw new Exception("Unable to randomize reps");
}
}
return newReps;
}
``````