Given an array that contains numbers and/or other nested arrays, write an algorithm to come up with a sum of these elements, multiplied by the depth (or how many arrays deep) you are. For example, what would you do with an input array that looks like: [ 2, 3, [ 9, [ 1, 2 ]], 4]
Sigiloso
For an input array of [ 2, 3, [ 9, [ 1, 2 ]], 4], The deepest array consists of [1, 2]. So summed, up we would get 1+2 (for the deepest array), multiplied by depth 3 = 9. The next level up, we’d have (9 + 9) * 2 = 36 And for the top level, (2 + 3 + 36 + 4) * depth level 1 = 45 (which is the ultimate result for this algorithm). I wrote this as an Objective-C NSArray extension. @implementation NSArray (DepthSum) { - (int) depthSum { return [self depthSum: self atDepth: 1]; } - (int) depthSum: (NSArray *)inputArray atDepth: currentDepth { int sum; for anObject in inputArray { // assuming the only objects that can be in the array // are either numbers or other arrays if ([anObject isKindOf: [NSArray class]]) { NSArray *subArray = (NSArray *)anObject; sum += [self depthSum: subArray atDepth: currentDepth+1]; } else { NSNumber *numberObject = (NSNumber *)anObject; sum += numberObject.intValue; } } return (sum * currentDepth); } }