How to generate non repeating random number

前端 未结 4 949
甜味超标
甜味超标 2021-01-07 04:45

I am trying to randomize numbers in an array. I am able to do that using arc4random() % [indexes count]

My problem is - If an array consists of 20 item

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 05:27

    Declare array that contains already generated number in extension or header file

    @property (strong, nonatomic)NSMutableArray *existingNums;
    @property (assign, nonatomic)NSInteger maxLimit;
    @property (assign, nonatomic)NSInteger minLimit;
    

    Then implement given code in implementation file

    @synthesize existingNums;
    @synthesize maxLimit;
    @synthesize minLimit;
    
    - (NSInteger)randomNumber {
    
        if(!existingNums)
            existingNums = [NSMutableArray array];
    
        while (YES) {
    
            NSNumber *randonNum = [NSNumber numberWithInteger:minLimit+arc4random()%maxLimit];
    
            if([existingNums containsObject:randonNum]) {
    
                if([existingNums count] == (maxLimit - minLimit))
                    return -1; // All possible numbers generated in the given range
    
                continue;
            }
    
            [existingNums addObject:randonNum];
    
            return [randonNum integerValue];
        }
    
        return -1;   // return error
    }
    

    Hope this will help you :)

提交回复
热议问题