Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
Tunyk Pavel Avatar asked Apr 30 '11 05:04

Tunyk Pavel


2 Answers

#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--;
       }
    }
}
like image 179
Julio Gorgé Avatar answered Sep 30 '22 11:09

Julio Gorgé


I made a caregory called NSArray+RandomSelection. Just import this category into a project, and then just use

NSArray *things = ...
...
NSArray *randomThings = [things randomSelectionWithCount:4];

Here's the implementation:

NSArray+RandomSelection.h

@interface NSArray (RandomSelection)
    - (NSArray *)randomSelectionWithCount:(NSUInteger)count;
@end

NSArray+RandomSelection.m

@implementation NSArray (RandomSelection)

- (NSArray *)randomSelectionWithCount:(NSUInteger)count {
    if ([self count] < count) {
        return nil;
    } else if ([self count] == count) {
        return self;
    }

    NSMutableSet* selection = [[NSMutableSet alloc] init];

    while ([selection count] < count) {
        id randomObject = [self objectAtIndex: arc4random() % [self count]];
        [selection addObject:randomObject];
    }

    return [selection allObjects];
}

@end
like image 34
mopsled Avatar answered Sep 30 '22 13:09

mopsled