-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay09.swift
66 lines (54 loc) · 1.21 KB
/
Day09.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import Foundation
import Tools
final class Day09Solver: DaySolver {
let dayNumber: Int = 9
struct Input {
let text: String
}
private func solve(text: String) -> (sum: Int, nrOfCancelled: Int) {
var inGarbage = false
var nextIsNegative = false
var groupDepth = 0
var sum = 0
var nrOfCancelled = 0
for character in text {
if inGarbage {
if character == ">" {
if nextIsNegative {
nextIsNegative = false
continue
} else {
inGarbage = false
}
} else if character == "!" {
nextIsNegative.toggle()
} else {
if !nextIsNegative {
nrOfCancelled += 1
}
nextIsNegative = false
}
} else {
if character == "{" {
groupDepth += 1
} else if character == "}" {
sum += groupDepth
groupDepth -= 1
} else if character == "<" {
inGarbage = true
nextIsNegative = false
}
}
}
return (sum: sum, nrOfCancelled: nrOfCancelled)
}
func solvePart1(withInput input: Input) -> Int {
solve(text: input.text).sum
}
func solvePart2(withInput input: Input) -> Int {
solve(text: input.text).nrOfCancelled
}
func parseInput(rawString: String) -> Input {
return .init(text: rawString.allLines().first!)
}
}