开发者

ObjectiveC random digits

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"
#define MAXDIGITCARDS 51
#define MINDIGITCARDS 0
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int userDigit=30;
        NSMutableArray* currentArray=[NSMutableArray new];  
        for (int a=0;a<userDigit;a++)
        {
            Evaluation *evaluation = [Evaluation new];
            int correctN开发者_JS百科umber = ((arc4random() % (MAXDIGITCARDS - MINDIGITCARDS)) + MINDIGITCARDS);
            [evaluation setCorrectNumber:correctNumber];
            [currentArray addObject:evaluation];
            [evaluation release];

        }
        [currentArray release];

    [pool drain];
    return 0;
}


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.


Have you seeded the random number generator? Something like:

srandom(time(NULL));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜