큰 NSArray 이름이 있는데 해당 배열에서 무작위로 4 개의 레코드 (이름)를 가져와야합니다. 어떻게해야합니까?nsarray에서 임의의 n 개 개체 (예 : 4) 가져 오기
11
A
답변
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--;
}
}
}
2
나는 NSArray+RandomSelection
이라는 간첩을 만들었습니다.
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
당신이 스위프트 프레임 워크를 선호하는 경우 : 그냥 프로젝트에이 범주를 가져온 다음 여기
NSArray *things = ...
...
NSArray *randomThings = [things randomSelectionWithCount:4];
를 사용하여 구현입니다 t 모자는 또한 더 편리한 기능을 체크 아웃 할 수 있습니다. HandySwift. 그런 다음 카르타고를 통해 프로젝트 에 추가 다음과 같이 사용할 수 있습니다 :
import HandySwift
let names = ["Harry", "Hermione", "Ron", "Albus", "Severus"]
names.sample() // => "Hermione"
번에 다수의 임의 요소를 얻을 수있는 옵션도 있습니다 :
names.sample(size: 3) // => ["Ron", "Albus", "Harry"]
나는 희망이 도움이 !
시드를 잊지 마세요 ... –
사실 저는 rand()를 arc4random()으로 대체했습니다. arc4random()은 우수하고 시드가 필요하지 않습니다. –
고맙습니다. 정상적으로 작동합니다. 그러나, 나는 pickedNames가 NSMutableArray 여야한다고 생각한다. –