-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2b732f8
commit 5a20ba4
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
} | ||
} |