Multiple random number requirement

I'm trying to create a mastermind style game to create my iOS skills. I am trying to create 6 random numbers between 0 and 9 using the following. I get different numbers when I start at different times, but all 6 numbers are always the same with every run.

NSNumber *n1 = [[NSNumber alloc]initWithInt:(random() % 10)];
NSNumber *n2 = [[NSNumber alloc]initWithInt:(random() % 10)];
NSNumber *n3 = [[NSNumber alloc]initWithInt:(random() % 10)];
NSNumber *n4 = [[NSNumber alloc]initWithInt:(random() % 10)];
NSNumber *n5 = [[NSNumber alloc]initWithInt:(random() % 10)];
NSNumber *n6 = [[NSNumber alloc]initWithInt:(random() % 10)];

Any help would be very helpful.

+3
source share
1 answer

Most likely, you forgot to plant a random generator (i.e. add the following line before generating random numbers):

srandom(time(NULL));

In any case, on the iPhone you should use the arc4random () function - it provides much better results and does not require seeding:

NSNumber *n1 = [[NSNumber alloc]initWithInt:(arc4random() % 10)];
+6
source

All Articles