2012-05-12 6 views
0

可能性の重複:
canonical way to randomize an NSArray in Objective Ciphone:どのようにランダムに配列の要素を移動するための

次のように私は配列を持っていると仮定します。

shuffleArray = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E", nil]; 

と私は次のようにランダムに配列の要素の位置を変更したい:

shuffleArray = [[NSMutableArray alloc] initWithObjects:@"C",@"A",@"B",@"E",@"D", nil]; 

は、私はこれをどのように行うことができます。

事前に

ありがとう..

+0

このリンクに従うことができます:http://stackoverflow.com/questions/4349669/nsmutablearray-move-object-from-index-to-index –

+0

this http://stackoverflow.com/questions/5659718/shuffling-目的の配列の配列を使用すると問題を解決できます –

答えて

0
-(NSArray *)shuffleme 
{ 

NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]]; 

NSMutableArray *array1 = [self mutableCopy]; 
while ([array1 count] > 0) 
{ 
    int temp = arc4random() % [array1 count]; 
    id objectToMove = [array1 objectAtIndex:temp]; 
    [array addObject:objectToMove]; 
    [array1 removeObjectAtIndex:temp]; 
} 

    [array1 release]; 
    return array; 
} 

ホープ、これはこれは、2つのインデックスでオブジェクトを交換するためのものです

0
-(void)changeObjectAtIndex:(int)index1 index2:(int)index2 array:(NSMutableArray *)array 
{ 
    id objectAtIndex1=[array objectAtIndex:index1]; 
    [array insertObject:[array objectAtIndex:index2] atIndex:index1]; 
    [array insertObject:id atIndex:index2]; 
} 

..あなたに役立つ、あなたが正確にわかっている場合は、この機能を再帰的に行うことができますどこで特定のオブジェクトが必要ですか。しかし、あなたが無作為に望むなら、あなたはNitの方法を採用することができます。

ランダムでもを行うことができます -

id newObject= [[[yourArray objectAtIndex:index] retain] autorelease]; 
[yourArray removeObjectAtIndex:index]; 
[yourArray insertObject:object atIndex:yourIndex]; 

は、オブジェクトを保持するために注意してください。

関連する問題