-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay13.swift
59 lines (45 loc) · 1.33 KB
/
Day13.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
import Foundation
import Tools
final class Day13Solver: DaySolver {
let dayNumber: Int = 13
struct Input {
let layers: [Int: Int]
}
@inline(__always)
private func positionOfScannerIsZero(timer: Int, depth: Int) -> Bool {
let cycleSize = (depth - 1) * 2
return timer % cycleSize == 0
}
private func calculateSeverity(startTime: Int, layers: [Int: Int]) -> (severity: Int, caught: Bool) {
let nrOfLayers = layers.keys.max()! + 1
var gotCaught = false
var result = 0
for layer in 0 ..< nrOfLayers {
guard let depth = layers[layer] else {
continue
}
if positionOfScannerIsZero(timer: layer + startTime, depth: depth) {
result += layer * depth
gotCaught = true
}
}
return (severity: result, caught: gotCaught)
}
func solvePart1(withInput input: Input) -> Int {
calculateSeverity(startTime: 4, layers: input.layers).severity
}
func solvePart2(withInput input: Input) -> Int {
for delay in 10 ..< 1_000_000_000 {
if calculateSeverity(startTime: delay, layers: input.layers).caught == false {
return delay
}
}
fatalError()
}
func parseInput(rawString: String) -> Input {
return .init(layers: rawString.allLines().reduce(into: [Int: Int]()) { result, line in
let components = line.components(separatedBy: ": ")
result[Int(components[0])!] = Int(components[1])!
})
}
}