내 응용 프로그램에서 카드 덱을 섞어 쓰려고하는데 다음 코드를 사용합니다. 갑판을 충분히 무작위화할 수 있습니까? 나는 거의 확실하다. 단지 다른 의견을 원할 것이다. 감사!카드 덱을 섞을 수있는 충분한 방법입니까?
for (int i = 0; i < 40000; i++) {
int randomInt1 = arc4random() % [deck.cards count];
int randomInt2 = arc4random() % [deck.cards count];
[deck.cards exchangeObjectAtIndex:randomInt1 withObjectAtIndex:randomInt2];
편집 : 향후 궁금한 점이 있거나 앞으로 다가올 경우가 있습니다. 이것이 제가 카드 더미를 뒤섞기 위해 사용했던 것입니다. 피셔 - 예이츠 알고리즘을 구현 한 것입니다. 포스트 @MartinR 여기에서 찾을 수있는 아래의 제안에서 나는 그것을 가지고 : [deck.cards 계산] 경우 What's the Best Way to Shuffle an NSMutableArray?가
NSUInteger count = [deck.cards count];
for (uint i = 0; i < count; ++i)
{
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = arc4random_uniform(nElements) + i;
[deck.cards exchangeObjectAtIndex:i withObjectAtIndex:n];
}
참조 http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle – Matt
두 개선 - 1) 스토어'돈 당신 때문에 루프 전에 변수에'[deck.cards 계산] 그 방법을 8 만 번 호출해야합니다. 2) 모듈러스가있는'arc4random' 대신'arc4random_uniform (count)'를 사용하십시오. – rmaddy
* "갑판을 충분히 랜덤화할 수 있습니까?"*는 확률 이론의 전문가에게 더 수학적인 질문입니다. NSArray에 대한 Fisher-Yates 알고리즘의 구현은 다음과 같이 찾을 수 있습니다. [NSMutableArray를 섞는 가장 좋은 방법은 무엇입니까?] (http://stackoverflow.com/questions/56648/whats-the-best-way- to-shuffle-an-nsmutablearray). –