Re: Simple way to traverse 2D array?
Re: Simple way to traverse 2D array?
- Subject: Re: Simple way to traverse 2D array?
- From: Mark Ritchie <email@hidden>
- Date: Tue, 24 Feb 2009 00:05:29 -0500
On 23-Feb-09, at 7:36 PM, Ashley Perrien wrote:
I can't think of a way to nest the loops if I don't know how deeply
to nest them.
Hey Ashley!
Thanks! This was a fun diversion while I take a break from looking
for a gig! ;-) One solution is to use a second array which keeps the
indices. That way, on each iteration, you know where you are on each
array. Then the only fun part is to pay attention to roll over when
incrementing each index!
Here's an implementation which illustrates my idea. While it works for
me, please check it's suitability to your purpose and please don't use
it for large arrays without additional memory management!
// Initialize the 2D array
NSMutableArray *arrays = [NSMutableArray array];
[arrays addObject:[NSArray arrayWithObjects:@"1", @"2", @"3", nil]];
[arrays addObject:[NSArray arrayWithObjects:@"A", @"B", @"C", @"D",
nil]];
[arrays addObject:[NSArray arrayWithObjects:@"Red", @"White",
@"Blue", nil]];
// Initialize the starting index in each array
NSMutableArray *indices = [NSMutableArray array];
for (int index = 0; index < [arrays count]; index++){
[indices addObject:[NSNumber numberWithInt:0]];
}
BOOL done = NO;
while(!done && ([arrays count] > 0)){
// Extract one item from each array
NSMutableArray *results = [NSMutableArray array];
for (int index = 0; index < [indices count]; index++){
NSArray *currentArray = [arrays objectAtIndex:index];
NSNumber *currentIndex = [indices objectAtIndex:index];
id currentObject = [currentArray objectAtIndex:[currentIndex
intValue]];
[results addObject:currentObject];
}
NSLog([results componentsJoinedByString:@", "]);
// Increment the indices, rolling over from inner most to outer most
for (int index = ([indices count] - 1); index >= 0; index--){
NSArray *currentArray = [arrays objectAtIndex:index];
NSNumber *currentIndex = [indices objectAtIndex:index];
int indexValue = [currentIndex intValue];
indexValue++;
if(indexValue == [currentArray count]){
indexValue = 0; // reset this index
if(index == 0){
done = YES; // we're done when we reset the outer most index
}
}
NSNumber *newIndex = [NSNumber numberWithInt:indexValue];
[indices replaceObjectAtIndex:index withObject:newIndex];
if(indexValue != 0){
break; // since this index didn't reset
}
}
}
Good luck!
Mark
__
Mark Ritchie
Cocoa and WebObjects Developer
Diamond Lake Consulting Inc.
Toronto, Ontario, Canada
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden