Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Shuffle NSMutableArray

I have a NSMutableArray called putNumberUsed. It contains the following objects @"blah1,@"blah2",@"blah3",@"blah4". I want to shuffle these objects randomly so for example if I chose:

 [putNumberUsed objectAtIndex:0] 

it would give me anything but "blah1". How would I go about doing this? The following is the code I used thus far:

NSMutableArray *putNumbersUsed = [[NSMutableArray alloc] arrayWithObjects:@"blah1",@"blah2",@"blah3",@"blah4",nil];
like image 619
Alex G Avatar asked Nov 30 '22 05:11

Alex G


1 Answers

I think, You can write a loop for that. Please check the following code,

for (int i = 0; i < putNumberUsed.count; i++) {
    int randomInt1 = arc4random() % [putNumberUsed count];
    int randomInt2 = arc4random() % [putNumberUsed count];
    [putNumberUsed exchangeObjectAtIndex:randomInt1 withObjectAtIndex:randomInt2];
}

I this this may be useful to you.

like image 184
Rajesh Avatar answered Dec 04 '22 07:12

Rajesh