Skip to content

Instantly share code, notes, and snippets.

@thexande
Created November 16, 2019 02:42
Show Gist options
  • Save thexande/306cf8bfd76ba06989dd782c59bc7aaa to your computer and use it in GitHub Desktop.
Save thexande/306cf8bfd76ba06989dd782c59bc7aaa to your computer and use it in GitHub Desktop.
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