How to generate non repeating random number

前端 未结 4 945
甜味超标
甜味超标 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:16

    As per your requirement....kindly check this code

    Make this a property

    @synthesize alreadyGeneratedNumbers;
    

    Add these methods in your .m

    -(int)generateRandomNumber{
    
        int TOTAL_NUMBER=20;
    
        int low_bound = 0;
        int high_bound = TOTAL_NUMBER;
        int width = high_bound - low_bound;
        int randomNumber = low_bound + arc4random() % width;
    
        return randomNumber;
    }
    
    
    -(IBAction)randomNumbers:(UIButton *)sender
    {
    
        NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:5];
    
        BOOL contains=YES;
        while ([shuffle count]<5) {
            NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
            //NSLog(@"->%@",generatedNumber);
    
            if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
                [shuffle addObject:generatedNumber];
                contains=NO;
                [alreadyGeneratedNumbers addObject:generatedNumber];
            }
        }
    
        NSLog(@"shuffle %@",shuffle);
        NSLog(@"Next Batch");
    
    
        if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
            NSLog(@"\nGame over, Want to play once again?");//or similar kind of thing.
            [alreadyGeneratedNumbers removeAllObjects];
        }
    
    
    }
    

    Still I feel you need to some changes like

    it will give you correct value, but what if user pressed 5th time?

    out of 20 numbers you already picked 4 sets of 5 number, on on 6th time it will be in loop to search for next set of numbers and will become infinite.

    So what you can do is, keep the track of shuffle and once it reaches the limit i.e, 20/5=4 disable the random button.

提交回复
热议问题