-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay22.swift
99 lines (76 loc) · 2.42 KB
/
Day22.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import Foundation
import Tools
final class Day22Solver: DaySolver {
let dayNumber: Int = 22
struct Input {
var initialSize: Size
var infectedNodes: Set<Point2D>
}
func solvePart1(withInput input: Input) -> Int {
var currentPosition = Point2D(x: input.initialSize.width / 2, y: input.initialSize.height / 2)
var currentDirection = Direction.north
var infectedNodes = input.infectedNodes
var numberOfInfections = 0
for _ in 0 ..< 10000 {
let isInfected = infectedNodes.contains(currentPosition)
if isInfected {
currentDirection = currentDirection.turned(degrees: .ninety)
infectedNodes.remove(currentPosition)
} else {
currentDirection = currentDirection.turned(degrees: .twoSeventy)
infectedNodes.insert(currentPosition)
numberOfInfections += 1
}
currentPosition = currentPosition.moved(to: currentDirection)
}
return numberOfInfections
}
func solvePart2(withInput input: Input) -> Int {
enum State {
case clean
case weakened
case infected
case flagged
}
var currentPosition = Point2D(x: input.initialSize.width / 2, y: input.initialSize.height / 2)
var currentDirection = Direction.north
var nodeStates: [Point2D: State] = [:]
for infectedNode in input.infectedNodes {
nodeStates[infectedNode] = .infected
}
var numberOfInfections = 0
for _ in 0 ..< 10_000_000 {
let state: State = nodeStates[currentPosition] ?? .clean
switch state {
case .clean:
currentDirection = currentDirection.turned(degrees: .twoSeventy)
nodeStates[currentPosition] = .weakened
case .weakened:
nodeStates[currentPosition] = .infected
numberOfInfections += 1
case .infected:
currentDirection = currentDirection.turned(degrees: .ninety)
nodeStates[currentPosition] = .flagged
case .flagged:
currentDirection = currentDirection.opposite
nodeStates.removeValue(forKey: currentPosition)
}
currentPosition = currentPosition.moved(to: currentDirection)
}
return numberOfInfections
}
func parseInput(rawString: String) -> Input {
let allLines = rawString.allLines()
var infectedNodes: Set<Point2D> = []
let height = allLines.count
let width = allLines.first!.count
for (y, line) in allLines.enumerated() {
for (x, char) in line.enumerated() {
if char == "#" {
infectedNodes.insert(.init(x: x, y: y))
}
}
}
return .init(initialSize: .init(width: width, height: height), infectedNodes: infectedNodes)
}
}