Sarreph
Sarreph

Reputation: 2015

Repeating arbitrary nested for loops

I've been trying for a few hours to work out an algorithm that can achieve the following conditions:

I think this is best explained with an example:

e.g. For three arrays NSArray *input = @[[@"cat",@"dog",@"mouse"],[@"apple",@"banana"],[@"green"]]

produce an output that goes something like this: @[ @"catapplegreen", @"catbananagreen", @"dogapplegreen", @"dogbananagreen", @"mouseapplegreen", @"mousebananagreen" ];

I've tried nesting for loops but can't think of a way of allowing there to be an arbitrary amount of loops, as there needs to be one loop or 'level' per array in the input.

If anyone has any advice (even just pointers of what to look into to tackle this problem) I'd be most grateful.

Upvotes: 1

Views: 84

Answers (1)

Evan
Evan

Reputation: 750

So basically what I think you want to do it a Depth-First Traversal of your data.

Which you could do with a function such as

- (void)DepthFirstOnString:(NSString *)string children:(NSArray *)children {
    if (children.count < 1) {
        // You're finished
        NSLog(@"%@", string);
        return;
    } else {
        // Keep going
        NSArray *next = children[0];
        NSMutableArray *remaining = [children mutableCopy];
        [remaining removeObject:next];

        [next enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSMutableString *currentString = [string mutableCopy];
            [currentString appendString:obj];

            [self DepthFirstOnString:currentString children:remaining];
        }];
    }
}

being called by this code:

NSArray *input =  @[@[@"cat",@"dog",@"mouse"], @[@"apple",@"banana"], @[@"green"]];

NSArray *first = input[0];
NSMutableArray *remaining = [input mutableCopy];
[remaining removeObject:first];

[first enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [self DepthFirstOnString:obj children:remaining];
}];

Not the neatest code but hopefully gives you an idea of where to take it.

Upvotes: 2

Related Questions