From 57fff6d82985be335590556e9cd1320ae875c7a2 Mon Sep 17 00:00:00 2001 From: alexchao26 Date: Sun, 27 Dec 2020 15:52:15 -0500 Subject: [PATCH] 2015-day20: slow-ish solution for infinite elves delivering to infinite houses --- 2015/day20/main.go | 54 +++++++++++++++++++++++++++++++++++++++++ 2015/day20/main_test.go | 26 ++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 2015/day20/main.go create mode 100644 2015/day20/main_test.go diff --git a/2015/day20/main.go b/2015/day20/main.go new file mode 100644 index 0000000..fb44b81 --- /dev/null +++ b/2015/day20/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "flag" + "fmt" + "math" + + "github.com/alexchao26/advent-of-code-go/cast" + + "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 := infiniteElvesAndHouses(util.ReadFile("./input.txt"), part) + fmt.Println("Output:", ans) +} + +func infiniteElvesAndHouses(input string, part int) int { + targetNum := cast.ToInt(input) + + for house := 1; house < math.MaxInt32; house++ { + var gifts int + for _, factor := range getFactors(house) { + if part == 1 { + gifts += factor * 10 + } else if part == 2 && house/factor <= 50 { + // for part 2, ensure that this is the 50th or less house that + // the elf has visited before adding gifts + gifts += factor * 11 + } + } + if gifts >= targetNum { + return house + } + } + + panic("expect return from loop") +} + +func getFactors(num int) []int { + var factors []int + sqrt := int(math.Sqrt(float64(num))) + for i := 1; i <= sqrt; i++ { + if num%i == 0 { + factors = append(factors, i, num/i) + } + } + return factors +} diff --git a/2015/day20/main_test.go b/2015/day20/main_test.go new file mode 100644 index 0000000..e50f72a --- /dev/null +++ b/2015/day20/main_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "testing" + + "github.com/alexchao26/advent-of-code-go/util" +) + +func Test_infiniteElvesAndHouses(t *testing.T) { + tests := []struct { + name string + input string + part int + want int + }{ + {"part1 actual", util.ReadFile("input.txt"), 1, 776160}, + {"part2 actual", util.ReadFile("input.txt"), 2, 786240}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := infiniteElvesAndHouses(tt.input, tt.part); got != tt.want { + t.Errorf("infiniteElvesAndHouses() = %v, want %v", got, tt.want) + } + }) + } +}