day 18 part 1
This commit is contained in:
parent
6fa8fe6d87
commit
76cf560634
2 changed files with 138 additions and 0 deletions
45
day18/main.swift
Normal file
45
day18/main.swift
Normal file
|
@ -0,0 +1,45 @@
|
|||
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? {
|
||||
guard var result = primary() else { return nil }
|
||||
while let op = self.op() {
|
||||
guard let second = primary() else { fatalError() }
|
||||
switch op {
|
||||
case "+": result += second
|
||||
case "*": result *= second
|
||||
default: fatalError()
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
var result = 0
|
||||
while let e = scanner.expression() {
|
||||
result += e
|
||||
}
|
||||
|
||||
print(result)
|
Loading…
Add table
Add a link
Reference in a new issue