Take the 2-minute tour ×

I need some help. I want to generate numbers.But my numbers repeated. how can I make the numbers don't repeat? My code below. Thanks

#import <Foundation/Foundation.h>
#import "Evaluation.h"
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int userDigit=30;
        NSMutableArray* currentArray=[NSMutableArray new];  
        for (int a=0;a<userDigit;a++)
            Evaluation *evaluation = [Evaluation new];
            int correctNumber = ((arc4random() % (MAXDIGITCARDS - MINDIGITCARDS)) + MINDIGITCARDS);
            [evaluation setCorrectNumber:correctNumber];
            [currentArray addObject:evaluation];
            [evaluation release];

        [currentArray release];

    [pool drain];
    return 0;
share|improve this question
Can you post the setCorrectNumber function? or is it synthesized? –  Joze Mar 31 '11 at 8:08
What is 'arc4random'? Why aren't you using random() from the standard C library? –  jv42 Mar 31 '11 at 8:09
CorrectNumber synthesized. In this class one variable int CorrectNumber –  Anton Mar 31 '11 at 8:15
I study Objective C and try to make with arc4random –  Anton Mar 31 '11 at 8:16
@jv42 arc4random() is generally acknowledged as a better (as in, "statistically-speaking more randomly random") generator than random() and srandom(). –  akosma Mar 31 '11 at 8:24
show 2 more comments

2 Answers

up vote 1 down vote accepted

If by 'not repeat' you mean you want all 30 numbers to be different from each other, then each time you generate a number see if it already exists in currentArray. If it does, generate another one. Repeat until you get one that you haven't had already.

Alternatively (since it looks like you are shuffling cards) look at something like the Fisher-Yates shuffle.

share|improve this answer
add comment

Have you seeded the random number generator? Something like:

share|improve this answer
add comment

Your Answer


