これは、(私は配列内の初期位置を示して パズルオブジェクト変数のインデックスに追加した。NSMutableArrayのですが、それはパズルのオブジェクトを含むオブジェクトパズル)NSArraysまたはNSMutableArrays をシャッフルする最も簡単かつ最速の方法です
int randomSort(id obj1, id obj2, void *context) {
// returns random number -1 0 1
return (random()%3 - 1);
}
- (void)shuffle {
// call custom sort function
[puzzles sortUsingFunction:randomSort context:nil];
// show in log how is our array sorted
int i = 0;
for (Puzzle * puzzle in puzzles) {
NSLog(@" #%d has index %d", i, puzzle.index);
i++;
}
}
ログ出力:
#0 has index #6
#1 has index #3
#2 has index #9
#3 has index #15
#4 has index #8
#5 has index #0
#6 has index #1
#7 has index #4
#8 has index #7
#9 has index #12
#10 has index #14
#11 has index #16
#12 has index #17
#13 has index #10
#14 has index #11
#15 has index #13
#16 has index #5
#17 has index #2
あなたにもobj2のでobj1と比較して、あなたが 可能な値を返すようにしたいかを決めることがあります:
- NSOrderedAscending = -1
- NSOrderedSame = 0
- NSOrderedDescending = 1
ここには、Swiftの実装があります:http://iosdevelopertips.com/swift-code/swift-shuffle-array-typehtml –
あなたのシャッフルアルゴリズムに関してこの問題を見てみましょう:[実際のシャッフルの問題](http://stackoverflow.com/questions/96840/real-world-problems-with-naive-shuffling) – craigb
現在のベストは[Fisher-Yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)です:for(NSUInteger i = self.count; i> 1; i--) [self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)]; ' –