-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (56 loc) · 1.14 KB
/
main.go
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
package main
import (
input "aoc2020/inpututils"
"fmt"
"strconv"
"strings"
)
func main() {
fmt.Println("--- Part One ---")
fmt.Println(Part1("input.txt"))
fmt.Println("--- Part Two ---")
fmt.Println(Part2("input.txt"))
}
func Part1(filename string) int {
lines := input.ReadLines(filename)
earliestTime := toInt(lines[0])
buses := lines[1]
shortestWait, currentBusId := int(^uint(0)>>1), 0
for _, bus := range strings.Split(buses, ",") {
if bus == "x" {
continue
}
b := toInt(bus)
wait := (((earliestTime / b) * b) + b - earliestTime)
if wait < shortestWait {
shortestWait = wait
currentBusId = b
}
}
return shortestWait * currentBusId
}
func Part2(filename string) int {
lines := input.ReadLines(filename)
buses := strings.Split(lines[1], ",")
runningProduct, earliestBus := 1, 0
for idx, bus := range buses {
if bus == "x" {
continue
}
for (earliestBus+idx)%toInt(bus) != 0 {
earliestBus += runningProduct
}
runningProduct *= toInt(bus)
}
return earliestBus
}
func check(err error) {
if err != nil {
panic(err)
}
}
func toInt(s string) int {
i, err := strconv.Atoi(s)
check(err)
return i
}