iOS: How do I generate 8 unique random integers?

前端 未结 6 1014
天命终不由人
天命终不由人 2020-12-03 15:10

I need to generate 8 random integers, but they need to be unique, aka not repeated.

For example, I want 8 numbers within the range 1 to 8.

I\'ve seen arc4ran

6条回答
  •  情话喂你
    2020-12-03 16:04

    Checking for already generated numbers is potentially expensive (theoretically, it could take forever.) However, this is a solved problem. You want a shuffling algorithm, like the Fisher-Yates_shuffle

    On iOS probably something like:

    NSMutableArray *randSequence = [[NSMutableArray alloc] initWithCapacity:8];
    for (int ii = 1; ii < 9; ++ii)
        [randSequence addObject:[NSNumber numberWithInt:ii]];
    
    for (int ii = 8; ii > 0; --ii) {
        int r = arc4random() % (ii + 1);
        [randSequence exchangeObjectAtIndex:ii withObjectAtIndex:r];
    
    // you can now iterate over the numbers in `randSequence` to get
    // your sequence in random order
    

提交回复
热议问题