Created
November 6, 2017 03:04
-
-
Save AdrianFerreyra/fa6cc6506d284efc8bf4983b94cbae3b to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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] | |
*/ | |
import Foundation | |
func sumInts(in array: [Any], level: Int = 1) -> Int { | |
let sum = array | |
.flatMap { $0 as? Int } | |
.reduce(0, +) | |
let innerArrays = array | |
.flatMap { $0 as? [Any] } | |
return sum * level + (innerArrays.count > 0 ? innerArrays.reduce(0) { $0 + sumInts(in: $1, level: level + 1) } : 0 ) | |
} | |
let array: [Any] = [1,[2,3],4,[2],[3,[3,[3],2],2]] | |
let sum = sumInts(in: array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great code, can we add a guard on top so that we will have simpler return statement? something like this: