2011-04-30 1 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

시드를 잊지 마세요 ... –

+3

사실 저는 rand()를 arc4random()으로 대체했습니다. arc4random()은 우수하고 시드가 필요하지 않습니다. –

+0

고맙습니다. 정상적으로 작동합니다. 그러나, 나는 pickedNames가 NSMutableArray 여야한다고 생각한다. –

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

무작위 선택을위한 처리가 배열보다 큽니다. 첫 번째 5 줄 대신 다음을 사용합니다. if ([self count] miho

+0

배열에 고유 한 원소가 '개수'보다 적 으면 끝내고 무한 루프가됩니다 – Pieter

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"] 

나는 희망이 도움이 !

+0

임의의 숫자 목록을 사용하는 방법을 보여줄 필요가 있으므로 질문에 대답하지 않습니다. 선택한 배열을 생성하려면 큰 배열의 이름을 선택하십시오. – Droppy

+1

내 대답이 오도 된 것 같습니다. 이름 배열을 숫자 배열 대신 예제로 사용하도록 업데이트했습니다. 똑같은 방식으로 작동합니다. 단지 다른 유형의 배열입니다. 나는 그것이 지금 분명하기를 바란다. – Dschee