Skip to content

Instantly share code, notes, and snippets.

@YuliiaVeres
Last active April 4, 2016 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YuliiaVeres/2ea505258f8f14cc97f8fad901d44620 to your computer and use it in GitHub Desktop.
Save YuliiaVeres/2ea505258f8f14cc97f8fad901d44620 to your computer and use it in GitHub Desktop.
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. (Let's consider we are in the ViewController)
// Suppose we are in some ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *first = @[@(1), @(2), @(3)];
NSArray *second = @[first, @(4)];
NSArray *third = @[@(6), @(7)];
NSArray *arrayToTest = @[second, @(5), third, @(8)];
NSArray *result = [self processArray:arrayToTest];
NSLog(@"Result array: %@", result);
}
#pragma mark - Searching for array element or integer element
- (NSArray *)processArray:(NSArray *)elementsArray
{
NSMutableArray *resultArray = [NSMutableArray new];
for (id element in elementsArray)
{
if ([element isKindOfClass:[NSArray class]])
{
NSArray *arrayResults = [self processArray:element];
[resultArray addObjectsFromArray:arrayResults];
}
else
[resultArray addObject:element];
}
return resultArray.copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment