Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created March 9, 2019 09:30
Show Gist options
  • Save jmcd/1e7d2c80d36b0d95fcd2cb125f52b480 to your computer and use it in GitHub Desktop.
Save jmcd/1e7d2c80d36b0d95fcd2cb125f52b480 to your computer and use it in GitHub Desktop.
let tokens = "15 7 1 1 + - / 3 * 2 1 1 + + -".split(separator: " ").map { String($0) }
let operators: [String: (Int, Int) -> (Int)] = [
"+" : (+),
"-" : (-),
"*" : (*),
"/" : (/)
]
let outstack = tokens.reduce([Int]()) { (stack, token) in
var mutableStack = stack
if let opr = operators[token] {
let op2 = mutableStack.popLast()!
let op1 = mutableStack.popLast()!
let result = opr(op1, op2)
mutableStack.append(result)
} else if let op = Int(token) {
mutableStack.append(op)
}
return mutableStack
}
outstack.last
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment