Created
November 16, 2019 02:42
-
-
Save thexande/306cf8bfd76ba06989dd782c59bc7aaa to your computer and use it in GitHub Desktop.
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
struct Stack<T> { | |
private var storage = [T]() | |
mutating func push(_ item: T) { | |
storage.append(item) | |
} | |
mutating func pop() -> T? { | |
return storage.removeLast() | |
} | |
func peek() -> T? { | |
return storage.last | |
} | |
var count: Int { | |
return storage.count | |
} | |
} | |
final class SumOperationManager { | |
private var sumOperations = Stack<[Any]>() | |
func sum(_ collection: [Any]) -> Int { | |
sumOperations.push(collection) | |
var sum = 0 | |
repeat { | |
guard let items = sumOperations.pop() else { return sum } | |
for item in items { | |
if let item = item as? Int { | |
sum += item | |
} else if let item = item as? [Any] { | |
sumOperations.push(item) | |
} | |
} | |
} while sumOperations.count > 0 | |
return sum | |
} | |
} | |
let op = SumOperationManager() | |
op.sum([1, 1, 1, [1, 1, [1]]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment