Skip to content

Commit d20b015

Browse files
committed
day22: solve part two
1 parent 918ef20 commit d20b015

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

day22/example3.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
1
2+
2
3+
3
4+
2024

day22/main.go

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,53 @@ func calculateNextSecret(secret int) int {
3535
return step3
3636
}
3737

38+
type changesHash string
39+
40+
func hashChanges(changes []int) changesHash {
41+
return changesHash(fmt.Sprintf("%v", changes))
42+
}
43+
3844
func main() {
3945
var sum int
46+
var totalGain = make(map[changesHash]int)
4047
for _, initialSecret := range readInitialSecrets() {
4148
var secret = initialSecret
49+
var changes []int
50+
var buyerGain = make(map[changesHash]int)
4251
for i := 0; i < 2000; i++ {
52+
var oldPrice = secret % 10
4353
secret = calculateNextSecret(secret)
54+
var price = secret % 10
55+
var change = price - oldPrice
56+
if len(changes) == 4 {
57+
changes = changes[1:4]
58+
}
59+
changes = append(changes, change)
60+
var hash = hashChanges(changes)
61+
if _, ok := buyerGain[hash]; !ok {
62+
buyerGain[hash] = price
63+
}
4464
}
4565
sum += secret
4666
fmt.Printf("%d: %d\n", initialSecret, secret)
67+
for hash, price := range buyerGain {
68+
var totalPrice int
69+
if oldTotalPrice, ok := totalGain[hash]; ok {
70+
totalPrice += oldTotalPrice
71+
}
72+
totalPrice += price
73+
totalGain[hash] = totalPrice
74+
}
75+
}
76+
fmt.Printf("sum of 2000th secrets: %d\n", sum)
77+
78+
var maxHash changesHash
79+
var maxPrice int
80+
for hash, price := range totalGain {
81+
if price > maxPrice {
82+
maxHash = hash
83+
maxPrice = price
84+
}
4785
}
48-
fmt.Printf("sum of secrets: %d\n", sum)
86+
fmt.Printf("max gain is %d for sequence %s\n", maxPrice, maxHash)
4987
}

0 commit comments

Comments
 (0)