3

I'm trying to create a mastermind style game to build up my iOS objective c skills. I'm trying to create 6 random numbers between 0 and 9 using the following. I get different numbers when run at different times but all 6 numbers are always the same on each 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 useful.

1
  • 1
    possible duplicate of 1 2 Commented Jun 12, 2011 at 12:06

1 Answer 1

6

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

srandom(time(NULL)); 

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

NSNumber *n1 = [[NSNumber alloc]initWithInt:(arc4random() % 10)]; 
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks. Turned out it was me being a muppet. Getting the numbers back out of an array for an alert, I forgot to change the index.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.