advent-of-code

Perserverance, or the lack thereof

git clone git://git.shimmy1996.com/advent-of-code.git
commit 65de606774a770e14adfc354c1701d15f62d985a
parent a14bc77d91cf2efc72d2f16c8eb8a1a9c90ae632
Author: Shimmy Xu <shimmy.xu@shimmy1996.com>
Date:   Tue, 15 Dec 2020 20:06:53 -0600

Add 2020 day 15

Diffstat:
A2020/day15/main.go | 40++++++++++++++++++++++++++++++++++++++++
1 file changed, 40 insertions(+), 0 deletions(-)
diff --git a/2020/day15/main.go b/2020/day15/main.go
@@ -0,0 +1,40 @@
+package main
+
+import (
+	"fmt"
+)
+
+func main() {
+	input := []int{11, 0, 1, 10, 5, 19}
+	// 870
+	fmt.Println(part1(input))
+	// 9136
+	fmt.Println(part2(input))
+}
+
+func memoryGame(input []int, target int) int {
+	lastAppear := map[int]int{}
+	for i, v := range input[:len(input)-1] {
+		lastAppear[v] = i + 1
+	}
+	curr := input[len(input)-1]
+	for i := len(input); i < target; i++ {
+		prev := curr
+		if lastAppear[prev] == 0 {
+			curr = 0
+		} else {
+			curr = i - lastAppear[prev]
+		}
+		// Only update after we have the next number
+		lastAppear[prev] = i
+	}
+	return curr
+}
+
+func part1(input []int) int {
+	return memoryGame(input, 2020)
+}
+
+func part2(input []int) int {
+	return memoryGame(input, 30_000_000)
+}