-
Notifications
You must be signed in to change notification settings - Fork 0
/
aoc.go
104 lines (94 loc) · 1.46 KB
/
aoc.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
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
100
101
102
103
104
package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"strconv"
"strings"
)
func main() {
n, err := ParseNotes(os.Stdin)
if err != nil {
log.Fatal(err)
}
wait := func(id int) int {
return id - n.Depart%id
}
var next int = math.MaxInt64
for _, id := range n.IDs {
if id == 0 {
continue
}
if wait(id) < wait(next) {
next = id
}
}
fmt.Printf("Next bus: %d (in %d minutes)\n", next, wait(next))
fmt.Println("Product:", next*wait(next))
var (
t = 0
m = 1
)
for i, id := range n.IDs {
if id == 0 {
continue
}
for (t+i)%id != 0 {
t += m
}
m = lcm(m, id)
}
fmt.Printf("Content-winning timestamp: %d\n", t)
}
type Notes struct {
Depart int
IDs []int
}
func ParseNotes(r io.Reader) (Notes, error) {
var n Notes
buf, err := ioutil.ReadAll(r)
if err != nil {
return n, err
}
s := string(bytes.TrimSpace(buf))
sp := strings.Split(s, "\n")
if len(sp) != 2 {
return n, errors.New("need exactly two lines of input")
}
n.Depart, err = strconv.Atoi(sp[0])
if err != nil {
return n, err
}
sp = strings.Split(sp[1], ",")
for _, s := range sp {
var id int
if s != "x" {
id, err = strconv.Atoi(s)
if err != nil {
return n, err
}
}
n.IDs = append(n.IDs, id)
}
return n, nil
}
func abs(a int) int {
if a > 0 {
return a
}
return -a
}
func lcm(a, b int) int {
return abs(a * (b / gcd(a, b)))
}
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}