Skip to content
This repository was archived by the owner on Dec 28, 2024. It is now read-only.

Commit 7b84516

Browse files
committed
Add solution day 22 part 2
1 parent 71a8bc7 commit 7b84516

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ automatically rebuilt and redeployed every time the `common` module or their own
5454
| 06 | ⭐ ⭐ | 19 | ⭐ ⭐ |
5555
| 07 | ⭐ ⭐ | 20 | ⭐ ⭐ |
5656
| 08 | ⭐ ⭐ | 21 | |
57-
| 09 | ⭐ ⭐ | 22 | |
57+
| 09 | ⭐ ⭐ | 22 | |
5858
| 10 | ⭐ ⭐ | 23 | |
5959
| 11 | ⭐ ⭐ | 24 | |
6060
| 12 | ⭐ ⭐ | 25 | |

solutions/day22/main.go

+68-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
)
99

1010
func main() {
11-
common.Setup(22, part1, nil)
11+
common.Setup(22, part1, part2)
1212
}
1313

1414
func part1(
@@ -30,6 +30,73 @@ func part1(
3030
return fmt.Sprintf("Sum of all secret numbers after 2k rounds: %d", sum)
3131
}
3232

33+
type priceDiff struct {
34+
diff int
35+
price int
36+
}
37+
38+
func part2(
39+
input string,
40+
) string {
41+
secrets, err := parse(input)
42+
if err != nil {
43+
return fmt.Sprintf("Failed to parse input: %v", err)
44+
}
45+
46+
allKeys := make(map[string]bool)
47+
allPriceMaps := make([]map[string]int, len(secrets))
48+
49+
for i, secret := range secrets {
50+
ds := make([]priceDiff, 2000)
51+
price := priceOf(secret)
52+
visited := make(map[string]bool)
53+
priceMap := make(map[string]int)
54+
55+
for n := 0; n < 2000; n++ {
56+
secret = evolveSecretNumber(secret)
57+
newPrice := priceOf(secret)
58+
ds[n] = priceDiff{diff: newPrice - price, price: newPrice}
59+
price = newPrice
60+
}
61+
62+
for n := 3; n <= 1999; n++ {
63+
key := fmt.Sprintf(
64+
"%d,%d,%d,%d",
65+
ds[n-3].diff, ds[n-2].diff, ds[n-1].diff, ds[n].diff)
66+
if visited[key] {
67+
continue
68+
}
69+
70+
allKeys[key] = true
71+
visited[key] = true
72+
priceMap[key] = ds[n].price
73+
}
74+
allPriceMaps[i] = priceMap
75+
}
76+
77+
bestKey := ""
78+
bestSum := 0
79+
for key, _ := range allKeys {
80+
sum := 0
81+
for _, pm := range allPriceMaps {
82+
sum += pm[key]
83+
}
84+
85+
if sum > bestSum {
86+
bestSum = sum
87+
bestKey = key
88+
}
89+
}
90+
91+
return fmt.Sprintf("Max number of bananas %d (%s)", bestSum, bestKey)
92+
}
93+
94+
func priceOf(n int) int {
95+
s := strconv.Itoa(n)
96+
ch := s[len(s)-1]
97+
return int(ch - '0')
98+
}
99+
33100
func parse(
34101
input string,
35102
) ([]int, error) {

0 commit comments

Comments
 (0)