Get n random objects (for example 4) from nsarray

空扰寡人 提交于 2019-12-18 11:54:24

问题


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


回答1:


#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--;
       }
    }
}



回答2:


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



回答3:


If you prefer a Swift Framework that also has some more handy features feel free to checkout HandySwift. You can add it to your project via Carthage then use it like this:

import HandySwift    

let names = ["Harry", "Hermione", "Ron", "Albus", "Severus"]
names.sample() // => "Hermione"

There is also an option to get multiple random elements at once:

names.sample(size: 3) // => ["Ron", "Albus", "Harry"]

I hope this helps!



来源:https://stackoverflow.com/questions/5839881/get-n-random-objects-for-example-4-from-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!