Search code examples
objective-ciosrandomnsarray

Get n random objects (for example 4) from nsarray


I have a large NSArray of names, I need to get random 4 records (names) from that array, how can I do that?


Solution

  • #include <stdlib.h>
    
    NSArray* names = ...;
    NSMutableArray* pickedNames = [NSMutableArray new];
    
    int remaining = 4;
    
    if (names.count >= remaining) {
        while (remaining > 0) {
           id name = names[arc4random_uniform(names.count)];
    
           if (![pickedNames containsObject:name]) {
               [pickedNames addObject:name];
               remaining--;
           }
        }
    }