• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Simple way to traverse 2D array?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Simple way to traverse 2D array?


  • Subject: Re: Simple way to traverse 2D array?
  • From: Peter N Lewis <email@hidden>
  • Date: Tue, 24 Feb 2009 22:15:34 +0900

At 18:36 -0600 23/2/09, Ashley Perrien wrote:
This is relatively easy if I know how many arrays I'm working with (3 in this case) to simply nest the for loops but if I don't know how many arrays the primary array has, I can't think of a way to nest the loops if I don't know how deeply to nest them. Any suggestions on the best way to approach something like this?

You could use a simple recursion, something like this:

void Recurse( NSMutableArray* allresults, NSArray* arrays, int index, NSMutableArray* current )
{
if ( index >= [arrays count] ) {
[allresults addObject:current];
} else {
for ( id obj in [arrays objectAtIndex:index] ) {
NSMutableArray* c = [current mutableCopy];
[c addObject:obj];
Recurse( allresults, arrays, index+1, c );
[c release];
}
}
}


void Doit()
{
  // 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]];

NSMutableArray *allresults = [NSMutableArray array];
Recurse( allresults, arrays, 0, [NSMutableArray array] );
NSLog( @"%@", allresults );
}


Enjoy,
   Peter.

--
     Run macros from your iPhone with Keyboard Maestro Control!
       or take a break with Aragom Space War for your iPhone

Keyboard Maestro <http://www.keyboardmaestro.com/> Macros for your Mac
Aragom Space War <http://www.stairways.com/iphone/aragom> Don't get killed!
<http://www.stairways.com/>           <http://download.stairways.com/>
_______________________________________________

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


References: 
 >Simple way to traverse 2D array? (From: Ashley Perrien <email@hidden>)

  • Prev by Date: Re: View with Subviews + Drawing on top of everything
  • Next by Date: simple memory management question
  • Previous by thread: Re: Simple way to traverse 2D array?
  • Next by thread: (Almost)Newbie Question: Implementing / use a free available source code editor
  • Index(es):
    • Date
    • Thread