-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (66 loc) · 1.22 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"bufio"
"fmt"
"io"
"os"
"path"
"strconv"
"strings"
)
func input() *os.File {
input, err := os.Open(path.Join("2020", "15", "input.txt"))
if err != nil {
panic(err)
}
return input
}
func solve(r io.Reader) {
scanner := bufio.NewScanner(r)
chomp := func() string {
if !scanner.Scan() {
if scanner.Err() != nil {
panic(scanner.Err())
}
}
return scanner.Text()
}
raw := strings.Split(chomp(), ",")
numbers := make([]int, len(raw))
for i, rawNum := range raw {
intNum, err := strconv.Atoi(rawNum)
if err != nil {
panic(err)
}
numbers[i] = intNum
}
fmt.Println(game(numbers, 2020))
}
func game(starting []int, limit int) int {
memory := make(map[int]int)
next := 0
for i := 0; i < limit-1; i++ {
if i < len(starting) {
next = starting[i]
}
oldNext := next
age, ok := memory[next]
if !ok {
next = 0
} else {
next = i - age
}
memory[oldNext] = i
}
return next
}
func main() {
solve(strings.NewReader("0,3,6"))
solve(strings.NewReader("1,3,2"))
solve(strings.NewReader("2,1,3"))
solve(strings.NewReader("1,2,3"))
solve(strings.NewReader("2,3,1"))
solve(strings.NewReader("3,2,1"))
solve(strings.NewReader("3,1,2"))
solve(input())
}