From ab208bdb80a4a600d808ef041ac79151692942f6 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 22 Dec 2024 11:09:35 +0100 Subject: [PATCH] day22p1 --- day22p1/solution.go | 40 ++++++++++++++++++++++++++++++++++++++++ day22p1/solution_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 day22p1/solution.go create mode 100644 day22p1/solution_test.go diff --git a/day22p1/solution.go b/day22p1/solution.go new file mode 100644 index 0000000..c347dc9 --- /dev/null +++ b/day22p1/solution.go @@ -0,0 +1,40 @@ +package day22p1 + +import ( + "io" + "strconv" + + "aoc/utils" +) + +func Solve(r io.Reader) any { + lines := utils.ReadLines(r) + + sum := 0 + for _, line := range lines { + initialSecretNum, _ := strconv.Atoi(line) + newSecretNum := initialSecretNum + for i := 0; i < 2000; i++ { + newSecretNum = evolveSecretNum(newSecretNum) + } + sum += newSecretNum + } + + return sum +} + +func evolveSecretNum(initialSecretNum int) int { + secretNum := initialSecretNum + secretNum = prune(mix(secretNum, secretNum*64)) + secretNum = prune(mix(secretNum, secretNum/32)) + secretNum = prune(mix(secretNum, secretNum*2048)) + return secretNum +} + +func mix(a, b int) int { + return a ^ b +} + +func prune(a int) int { // modulo 16777216 (2^24) + return a & 0xFFFFFF +} diff --git a/day22p1/solution_test.go b/day22p1/solution_test.go new file mode 100644 index 0000000..d236c4b --- /dev/null +++ b/day22p1/solution_test.go @@ -0,0 +1,36 @@ +package day22p1 + +import ( + "strings" + "testing" + + "aoc/utils" +) + +var testInput = `1 +10 +100 +2024` + +func TestSolve(t *testing.T) { + tests := []struct { + input string + answer int + }{ + {testInput, 37327623}, + } + + if testing.Verbose() { + utils.Verbose = true + } + + for _, test := range tests { + r := strings.NewReader(test.input) + + result := Solve(r).(int) + + if result != test.answer { + t.Errorf("Expected %d, got %d", test.answer, result) + } + } +}