NSMutableArray の中身をシャッフルする方法のメモ
(XcodeのiOS6 Simulatorで試しています。)
ポイント
・exchangeObjectAtIndex withObjectAtIndex
サンプルコード
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
// テスト用の配列を用意する
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@”ace”, @”jack”, @”queen”, @”king”, nil];
// シャッフル(Fisher–Yates shuffle)
// 配列の中身をランダムに入れ替え
int count = [array count];
for (int i = count – 1; i > 0; i–) {
int randomNum = arc4random() % i;
[array exchangeObjectAtIndex:i withObjectAtIndex:randomNum];
}
NSLog(@”%@”, array);
}
@end