-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay19.swift
79 lines (67 loc) · 1.83 KB
/
Day19.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
import Foundation
import Tools
final class Day19Solver: DaySolver {
let dayNumber: Int = 19
struct Input {
var tiles: [Point2D: String] = [:]
}
private func walkPath(tiles : [Point2D: String]) -> (encounteredLetters: String, steps: Int) {
var currentDirection = Direction.south
var currentPoint = tiles.keys.filter { $0.y == 0 }.first!
var encounteredLetters = ""
var steps = 0
while let tile = tiles[currentPoint] {
switch tile {
case "|",
"-":
break
case "+":
switch currentDirection {
case .north,
.south:
if tiles[currentPoint.moved(to: .west)] != nil {
currentDirection = .west
} else if tiles[currentPoint.moved(to: .east)] != nil {
currentDirection = .east
} else {
fatalError()
}
case .west,
.east:
if tiles[currentPoint.moved(to: .north)] != nil {
currentDirection = .north
} else if tiles[currentPoint.moved(to: .south)] != nil {
currentDirection = .south
} else {
fatalError()
}
default: fatalError()
}
default:
if (AsciiCharacter.A ... AsciiCharacter.Z).contains(tile.first!.asciiValue!) {
encounteredLetters += tile
} else {
fatalError()
}
}
currentPoint = currentPoint.moved(to: currentDirection)
steps += 1
}
return (encounteredLetters: encounteredLetters, steps: steps)
}
func solvePart1(withInput input: Input) -> String {
walkPath(tiles: input.tiles).encounteredLetters
}
func solvePart2(withInput input: Input) -> Int {
walkPath(tiles: input.tiles).steps
}
func parseInput(rawString: String) -> Input {
var tiles: [Point2D: String] = [:]
for (y, line) in rawString.allLines().enumerated() {
for (x, char) in line.enumerated() where char != " " {
tiles[.init(x: x, y: y)] = String(char)
}
}
return .init(tiles: tiles)
}
}