Skip to content

Commit

Permalink
day22p2
Browse files Browse the repository at this point in the history
  • Loading branch information
gamersi committed Dec 22, 2024
1 parent ab208bd commit 3e5d606
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
60 changes: 60 additions & 0 deletions day22p2/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package day22p2

import (
"io"
"strconv"

"aoc/utils"
)

func Solve(r io.Reader) any {
lines := utils.ReadLines(r)

seqToProfit := make(map[[4]int]int)
visited := make(map[[4]int]bool)
for _, line := range lines {
var seq [4]int
clear(visited)
initialSecretNum, _ := strconv.Atoi(line)
newSecretNum := initialSecretNum
for i := 0; i < 2000; i++ {
prevPrice := newSecretNum % 10
newSecretNum = evolveSecretNum(newSecretNum)
price := newSecretNum % 10
diff := price - prevPrice
seq[0], seq[1], seq[2], seq[3] = seq[1], seq[2], seq[3], diff
if i < 3 {
continue
}
if !visited[seq] {
seqToProfit[seq] += price
visited[seq] = true
}
}
}

maxProfit := 0
for _, profit := range seqToProfit {
if profit > maxProfit {
maxProfit = profit
}
}

return maxProfit
}

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
}
36 changes: 36 additions & 0 deletions day22p2/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package day22p2

import (
"strings"
"testing"

"aoc/utils"
)

var testInput = `1
2
3
2024`

func TestSolve(t *testing.T) {
tests := []struct {
input string
answer int
}{
{testInput, 23},
}

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)
}
}
}

0 comments on commit 3e5d606

Please sign in to comment.