I need a method to generate 4 numbers positioned randonly in an array. This method must be able to be called several times. The code that I tried below seems to be working.. except that everytime I call it, it generates the very same numbers sequence.
At my header file:
NSMutableSet * numberSet;
NSArray * numbers;
Code file:
numberSet = [NSMutableSet setWithCapacity:4];
[self placeRandomLine];
numbers = [numberSet allObjects];
... using the generated array
[self placeRandomLine];
numbers = [numberSet allObjects];
... using the generated array
[self placeRandomLine];
numbers = [numberSet allObjects];
... using the generated array
Random Method:
-(void)placeRandomLine
{
[numberSet removeAllObjects];
while ([numberSet count] < 4 ) {
NSNumber * randomNumber = [NSNumber numberWithInt:(arc4random() % 4)];
[numberSet addObject:randomNumber];
}
}
I am sure I am missing something here..
Thanks for your help!
Use an ordered set:
NSLog output:
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:
NSLog output:
Alternatively using an ordered set