Created
March 9, 2019 09:30
-
-
Save jmcd/1e7d2c80d36b0d95fcd2cb125f52b480 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
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