I'm trying to make an array of objects in random, non repeating order. Using NSMutableSet for the heavy lifting as recommended here: http://stackoverflow.com/questions/2141121/how-to-check-repetition-of-numbers-in-an-array
I'm dumping them into an NSArray after creation to access them, but the NSArray doesn't stay in the order I placed them in the NSMutableSet. Making it more confusing is that it's not consistent.
My code:
NSArray *puzzleImages = [[NSArray alloc] initWithObjects:@"elephant.png", @"gorilla.png", @"lion.png", @"zebra.png", @"flamingo.png", @"hyena.png", @"seal.png", @"hippo.png", @"rhino.png", @"tiger.png", @"macaw.png", @"bear.png", nil];
NSArray *puzzleSounds = [[NSArray alloc] initWithObjects:@"elephant", @"gorilla", @"lion", @"zebra", @"flamingo", @"hyena", @"seal", @"hippo", @"rhino", @"tiger", @"macaw", @"bear", nil];
NSMutableSet *aImages1 = [NSMutableSet setWithCapacity:2];
NSMutableSet *aSounds1 = [NSMutableSet setWithCapacity:2];
NSMutableSet *aValues1 = [NSMutableSet setWithCapacity:2];
while([aImages1 count]<=1){
int Randnum1 = arc4random() % 11;
[aImages1 addObject:[puzzleImages objectAtIndex:Randnum1]];
[aSounds1 addObject:[puzzleSounds objectAtIndex:Randnum1]];
[aValues1 addObject:[NSNumber numberWithInt:Randnum1]];
NSLog(@"image:%@, sound:%@, value:%@",[puzzleImages objectAtIndex:Randnum1],[puzzleSounds objectAtIndex:Randnum1],[NSNumber numberWithInt:Randnum1]);
}
NSArray *arrayOfImages1 = [aImages1 allObjects];
NSLog(@"arrayOfImages1: %@",arrayOfImages1);
NSArray *arrayOfSounds1 = [aSounds1 allObjects];
NSLog(@"arrayOfSounds1: %@",arrayOfSounds1);
NSArray *arrayOfValues1 = [aValues1 allObjects];
NSLog(@"aValues1: %@",aValues1);
Here's my output:
2010-06-20 16:13:14.572 MatchGame[22675:207] image:lion.png, sound:lion, value:2
2010-06-20 16:13:14.574 MatchGame[22675:207] image:macaw.png, sound:macaw, value:10
2010-06-20 16:13:14.575 MatchGame[22675:207] arrayOfImages1: (
"lion.png",
"macaw.png")
2010-06-20 16:13:14.575 MatchGame[22675:207] arrayOfSounds1: (
macaw,
lion)
2010-06-20 16:13:14.576 MatchGame[22675:207] aValues1: {(
2,
10)}
How the heck did the Macaw sound end up above the lion sound? Course it doesn't always happen, but it breaks the game when it does. I'm sure I'm missing something silly, but spent enough time trying to figure it out on my own.