2020-12-18 07:32:01 +01:00
|
|
|
import Foundation
|
|
|
|
let input = loadData(day: 18)
|
|
|
|
let scanner = Scanner(string: input)
|
|
|
|
|
|
|
|
extension Scanner {
|
|
|
|
func primary() -> Int? {
|
|
|
|
if let num = scanInt() {
|
|
|
|
return num
|
|
|
|
}
|
|
|
|
|
|
|
|
if string("(") {
|
|
|
|
let result = expression()
|
|
|
|
if !string(")") {
|
|
|
|
fatalError()
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func op() -> String? {
|
|
|
|
scanString("+") ?? scanString("*")
|
|
|
|
}
|
|
|
|
|
|
|
|
func expression() -> Int? {
|
2020-12-18 07:52:26 +01:00
|
|
|
guard var result = addition() else { return nil }
|
|
|
|
while string("*"), let second = addition() {
|
|
|
|
result *= second
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
func addition() -> Int? {
|
2020-12-18 07:32:01 +01:00
|
|
|
guard var result = primary() else { return nil }
|
2020-12-18 07:52:26 +01:00
|
|
|
while string("+"), let second = primary() {
|
|
|
|
result += second
|
2020-12-18 07:32:01 +01:00
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var result = 0
|
|
|
|
while let e = scanner.expression() {
|
|
|
|
result += e
|
|
|
|
}
|
|
|
|
|
|
|
|
print(result)
|