-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay01.swift
More file actions
71 lines (57 loc) · 1.71 KB
/
Day01.swift
File metadata and controls
71 lines (57 loc) · 1.71 KB
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
import AOCCore
import Foundation
struct Day01: Day {
let title = "Secret Entrance"
var rawInput: String?
func part1() throws -> Int {
input().lines
.map(\.components)
.reduce((current: 50, total: 0)) { result, line in
var (current, total) = result
current += line.direction * line.steps
if current < 0 {
current = 100 + (current % 100)
} else if current > 100 {
current = current % 100
}
if current == 0 || current == 100 {
current = 0
total += 1
}
return (current, total)
}
.total
}
func part2() throws -> Int {
input().lines
.map(\.components)
.reduce((current: 50, total: 0)) { result, line in
var (current, total) = result
var delta = line.steps
while delta > 0 {
current += line.direction
delta -= 1
if current == 100 {
current = 0
}
if current == -1 {
current = 99
}
if current == 0 {
total += 1
}
}
return (current, total)
}
.total
}
}
private extension Line {
var components: (direction: Int, steps: Int) {
let direction = raw.prefix(1) == "L"
? -1
: 1
let steps = Int(raw.dropFirst()) ?? 0
return (direction, steps)
}
}