Shuffle Two NSMutableArray independently

Posted by Superman on Stack Overflow See other posts from Stack Overflow or by Superman
Published on 2012-10-16T04:06:50Z Indexed on 2012/10/16 23:01 UTC
Read the original article Hit count: 237

Filed under:
|
|

I'm creating two NSMutableArray in my viewDidLoad, I add it in a NSMutableDictionary. When I tried shuffling it with one array, It is okay. But the problem is when Im shuffling two arrays independently its not working,somehow the indexes got mixed up.

Here is my code for my array (I have two of these):

self.items1 = [NSMutableArray new];

for(int i = 0; i <= 100; i++) 
{ 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];

    NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"[Images%d.png", i]]; 
    if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){ 
        self.container = [[NSMutableDictionary alloc] init];
        [container setObject:[UIImage imageWithContentsOfFile:savedImagePath] forKey:@"items1"]; 
        [container setObject:[NSNumber numberWithInt:i] forKey:@"index1"];
        [items1 addObject:container];           
    } 
} 

NSLog(@"Count : %d", [items1 count]);  

[items1 enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
    NSLog(@"%@ images at index %d", object, index);
}];

then my shuffle code(Which I tried duplicating for the other array,but not working also):

   srandom(time(NULL));
    NSUInteger count = [items1 count];
    for (NSUInteger i = 0; i < count; ++i) {
        int nElements = count - i;
        int n = (random() % nElements) + i;
        [items1 exchangeObjectAtIndex:i withObjectAtIndex:n];
    }

How am I going to shuffle it using above code (or if you have other suggestions) with two arrays? Thanks

My other problem is when I tries subclassing the class for the shuffle method or either use the above code, their index mixed. For example:

Object: apple, ball, carrots, dog

Indexes: 1 2 3 4

but in my View when shuffled:

Object: carrots, apple, dog, balle

Indexes: 2 4 1 3

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about ios