Use an ordered set:
NSMutableOrderedSet *numberSet = [NSMutableOrderedSet new];
int setSize = 4;
while ([numberSet count] < setSize ) {
NSNumber * randomNumber = [NSNumber numberWithInt:arc4random_uniform(setSize)];
[numberSet addObject:randomNumber];
}
NSLog output:
numberSet: {(
2,
0,
1,
3
)}
Alternatively using an array or arbitrary numbers
Create an NSMutableArray
with the four integers.
Create an empty NSMutableArray
.
Use arc4random_uniform()
to pick one of the numbers in the first array, remove it and place it in the second array.
Repeat for all four numbers.
The second array will have the four numbers in a random order.
Example:
NSMutableArray *a0 = [@[@3, @5, @4, @8] mutableCopy];
NSMutableArray *a1 = [NSMutableArray new];
while (a0.count) {
int randomIndex = arc4random_uniform(a0.count);
NSNumber *randomValue = a0[randomIndex];
[a1 addObject:randomValue];
[a0 removeObject:randomValue];
}
NSLog(@"a1: %@", a1);
NSLog output:
a1: (
8,
5,
3,
4
)
Alternatively using an ordered set