1

誰かがビューをロードするたびに順序が混同されるように、NSMutableArray をシャッフルしようとしています。

-(void)viewDidLoadは次のコードを入れています(他のユーザーが提案したように):

NSMutableArray *shuffleTwo = [self.chosenTeamDict objectForKey:@"clubs"];

int random = arc4random() % [shuffleTwo count]; 
for (int i = 0; i < [shuffleTwo count]; i++) {
    [shuffleTwo exchangeObjectAtIndex:random withObjectAtIndex:i]; 
}

NSLog(@"%@", shuffleTwo);

しかし、これを実行してページを実行しようとすると、次のエラーが発生します。

2012-07-09 18:42:16.126 Kit-Quiz[6505:907] (null)
libc++abi.dylib: terminate called throwing an exception

この配列をシャッフルする新しい方法、またはこのエラーを回避する方法について私にアドバイスできる人はいますか..!? 私は iOS 5 用にビルドしており、Xcode45-DP1 を使用しています。前もって感謝します!

(編集)

この方法も試しましたが、同じエラーが発生します。

NSMutableArray *shuffledArray = [[NSMutableArray alloc] init];
    NSMutableArray *standardArray = [self.chosenTeamDict objectForKey:@"clubs"];

    for(int s = 0; s < [standardArray count]; s++){
        int random = arc4random() % s;
        [shuffledArray addObject:[standardArray objectAtIndex:random]];
    }

    NSLog(@"%@", shuffledArray);
4

3 に答える 3

1

フィッシャー・イェーツ・シャッフルを試してみてください。こんなふうになります:

int count = shuffledArray.count;

for(int i=count; i>0; i--) {

 int j = arc4random_uniform(count);

 [shuffledArray exchangeObjectAtIndex:j withObjectAtIndex:i];

}

配列が非 nil であり、すべてのエントリが割り当てられたオブジェクトであることを確認してください:)

出典: Fisher-Yates Shuffle

于 2012-07-09T18:34:39.310 に答える
1
NSMutableArray *standardArray = [self.chosenTeamDict objectForKey:@"clubs"];

int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[shuffledArray objectAtIndex:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
    int index = rand()%[indexes count];
    [shuffle addObject:[indexes objectAtIndex:index]];
    [indexes removeObjectAtIndex:index];
}
for (int i=0; i<[shuffle count]; i++) NSLog(@"%@", [shuffle objectAtIndex:i]);

NSLog(@"%@", shuffle);

^^ 答え

于 2012-07-09T20:05:06.377 に答える
0

まず、例外ブレークポイントを有効にする必要があります。左側のパネルの XCode で、ブレークポイント タブをクリックし、左下の「+」記号をクリックします -> 例外ブレークポイント -> 完了。

あなたの問題はここにあると思います:

int random = arc4random() % [shuffleTwo count]; 

[shuffleTwo count] がゼロと評価された場合 (shuffleTwo が nil の場合も)、ゼロ除算の例外がスローされます。編集: Objective-C ではそうではないようです。

于 2012-07-09T18:17:39.413 に答える