2011-04-30 49 views

回答

21
#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--; 
     } 
    } 
} 
+0

不要忘记种子... – 2011-04-30 06:00:50

+3

是的,我刚刚用arc4random()替换了rand(),这是优越的,不需要播种。 – 2011-04-30 06:03:59

+0

谢谢,它工作正常。但是,我认为,采摘名应该是NSMutableArray – 2011-04-30 06:05:54

2

我做了一个叫NSArray+RandomSelection类别..。就在这个类别导入到一个项目,然后只需用

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

这里的实现:

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 
+2

随机选择的处理大于数组不正确。我使用以下代替前5行:'if([self count] miho 2012-10-04 09:01:41

+0

如果数组中的'count'个数少于'count',那么最终会进入无限循环 – Pieter 2013-09-26 12:33:43

2

如果你喜欢一个斯威夫特框架 t帽子也有一些更方便的功能,可随时结账HandySwift。您可以通过迦太基将其添加到您的项目然后使用它是这样的:

import HandySwift  

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

还有一种选择,在一次得到多个随机元素:

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

我希望这有助于!

+0

这并不回答这个问题,因为您需要展示如何使用随机数列表选择大数组中的名称以创建拾取的名称数组。 – Droppy 2016-06-09 21:13:25

+1

看来我的回答是误导。我已经更新它以使用名称数组作为示例而不是数组数组。工作原理相同,只是一种不同类型的Array。我希望现在很清楚。 – Dschee 2016-06-09 21:21:01