From 228a6853e2c25287287cfb3596229cdbf784f150 Mon Sep 17 00:00:00 2001 From: alexchao26 Date: Wed, 16 Dec 2020 22:34:17 -0500 Subject: [PATCH] 2017-day17: brute force --- 2017/day17/main.go | 66 +++++++++++++++++++++++++++++++++++++++++ 2017/day17/main_test.go | 31 +++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 2017/day17/main.go create mode 100644 2017/day17/main_test.go diff --git a/2017/day17/main.go b/2017/day17/main.go new file mode 100644 index 0000000..c2d6c59 --- /dev/null +++ b/2017/day17/main.go @@ -0,0 +1,66 @@ +package main + +import ( + "flag" + "fmt" + "log" + + "github.com/alexchao26/advent-of-code-go/mathutil" + "github.com/alexchao26/advent-of-code-go/util" +) + +func main() { + var part int + flag.IntVar(&part, "part", 1, "part 1 or 2") + flag.Parse() + fmt.Println("Running part", part) + + ans := spinlock(util.ReadFile("./input.txt"), part) + util.CopyToClipboard(fmt.Sprintf("%v", ans)) + fmt.Println("Output:", ans) +} + +type llNode struct { + value int + next *llNode +} + +func spinlock(input string, part int) int { + steps := mathutil.StrToInt(input) + + lastNumToAdd := 2017 + if part == 2 { + lastNumToAdd = 50000000 + } + + current := &llNode{value: 0} + current.next = current + for i := 1; i <= lastNumToAdd; i++ { + for j := 0; j < steps; j++ { + current = current.next + } + + saveNext := current.next + current.next = &llNode{ + value: i, + next: saveNext, + } + current = current.next + + // progress log for part 2 brute force... + if i%1000000 == 0 { + log.Println(i, "steps done") + } + } + + // iterate to the node to find, then return the value of the next node + valueToFind := 2017 + if part == 2 { + valueToFind = 0 + } + for current.value != valueToFind { + current = current.next + } + + return current.next.value +} diff --git a/2017/day17/main_test.go b/2017/day17/main_test.go new file mode 100644 index 0000000..2f2fc76 --- /dev/null +++ b/2017/day17/main_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "testing" + + "github.com/alexchao26/advent-of-code-go/util" +) + +func Test_spinlock(t *testing.T) { + tests := []struct { + name string + input string + part int + want int + }{ + {"example_part1", "3", 1, 638}, + {"actual_part1", util.ReadFile("input.txt"), 1, 1547}, + {"actual_part2", util.ReadFile("input.txt"), 2, 31154878}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Logf("Running %s", tt.name) + if tt.name == "actual_part2" { + t.Log("This one could take a while, it has 50 million steps to run") + } + if got := spinlock(tt.input, tt.part); got != tt.want { + t.Errorf("spinlock() = %v, want %v", got, tt.want) + } + }) + } +}