Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created November 6, 2017 03:04
Show Gist options
  • Save AdrianFerreyra/fa6cc6506d284efc8bf4983b94cbae3b to your computer and use it in GitHub Desktop.
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.
/*
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)
@masiht
Copy link

masiht commented Nov 11, 2017

Great code, can we add a guard on top so that we will have simpler return statement? something like this:

guard  array.count > 0 else { return 0 }

...

return sum * level + innerArrays.reduce(0) { $0 + sumInts(in: $1, level: level + 1) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment