Skip to content

Commit

Permalink
Day 15 (Golang)
Browse files Browse the repository at this point in the history
  • Loading branch information
dwalker109 committed Dec 16, 2020
1 parent 2b732f8 commit 5a20ba4
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
49 changes: 49 additions & 0 deletions day15/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package main

import "fmt"

type recitation map[uint]num

func (r *recitation) remember(k uint, v uint) {
lookup, ok := (*r)[k]
if ok {
(*r)[k] = append(lookup, v)
} else {
(*r)[k] = num{v}
}
}

type num []uint

func (n num) turnsApart() uint {
if len(n) < 2 {
return 0
}
return n[len(n)-1] - n[len(n)-2]
}

func main() {
pt1 := solve([]uint{1, 0, 16, 5, 17, 4}, 2020)
pt2 := solve([]uint{1, 0, 16, 5, 17, 4}, 30000000)

fmt.Println("Part 1:", pt1)
fmt.Println("Part 2:", pt2)
}

func solve(s []uint, t uint) int {
var lastNum uint

rec := make(recitation)
for i, n := range s {
lastNum = n
rec.remember(n, uint(i+1))
}

for i := uint(len(rec) + 1); i <= t; i++ {
lastHist := rec[lastNum]
lastNum = lastHist.turnsApart()
rec.remember(lastNum, i)
}

return int(lastNum)
}
25 changes: 25 additions & 0 deletions day15/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import "testing"

func Test_part1(t *testing.T) {
exp := 438
got := solve([]uint{3, 2, 1}, uint(2020))
if exp != got {
t.Errorf("Part 1: expected %d, got %d", exp, got)
}
}

func Test_part2(t *testing.T) {
exp := 18
got := solve([]uint{3, 2, 1}, uint(30000000))
if exp != got {
t.Errorf("Part 1: expected %d, got %d", exp, got)
}
}

func Benchmark_part1(b *testing.B) {
for n := 0; n < b.N; n++ {
solve([]uint{3, 2, 1}, uint(2020))
}
}

0 comments on commit 5a20ba4

Please sign in to comment.