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

Commit 9ab0697

Browse files
committed
Add solution day 17 part 2
1 parent 5817dbe commit 9ab0697

File tree

2 files changed

+48
-23
lines changed

2 files changed

+48
-23
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ automatically rebuilt and redeployed every time the `common` module or their own
4949
| 01 | ⭐ ⭐ | 14 | ⭐ ⭐ |
5050
| 02 | ⭐ ⭐ | 15 | ⭐ ⭐ |
5151
| 03 | ⭐ ⭐ | 16 | ⭐ 🥸 |
52-
| 04 | ⭐ ⭐ | 17 | |
52+
| 04 | ⭐ ⭐ | 17 | |
5353
| 05 | ⭐ ⭐ | 18 | ⭐ ⭐ |
5454
| 06 | ⭐ ⭐ | 19 | |
5555
| 07 | ⭐ ⭐ | 20 | |

solutions/day17/main.go

Lines changed: 47 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package main
33
import (
44
"fmt"
55
"github.com/terminalnode/adventofcode2024/common"
6+
"strconv"
7+
"strings"
68
)
79

810
func main() {
@@ -28,38 +30,61 @@ func part2(
2830
return fmt.Sprintf("Failed to parse machine: %v", err)
2931
}
3032

31-
lenSeq := len(m.seq)
32-
initA := int64(0)
33+
maxIdx := len(m.seq) - 1
34+
octArr := make([]int, len(m.seq))
35+
octIdx := 0
3336
initB := m.b
3437
initC := m.c
35-
for initA = 0; true; initA++ {
36-
m.run(lenSeq)
37-
if compareSeqOut(m, lenSeq) {
38-
break
39-
}
40-
m.a = initA
38+
39+
for {
40+
seqIdx := maxIdx - octIdx
41+
42+
// Rig the machine
43+
octArr[octIdx] += 1
4144
m.b = initB
4245
m.c = initC
4346
m.out = m.out[:0]
44-
m.pos = 0
47+
48+
m.a, err = arrayToOct(octArr)
49+
if err != nil {
50+
return fmt.Sprintf("Failed to read %v as octal string: %v", octArr, err)
51+
}
52+
53+
// Run the program and verify output
54+
m.run(maxIdx + 1)
55+
correct := m.out[seqIdx] == m.seq[seqIdx]
56+
57+
if octIdx == maxIdx && correct {
58+
break
59+
} else if correct {
60+
octIdx++
61+
octArr[octIdx] = -1
62+
}
63+
64+
for octArr[octIdx] == 7 {
65+
octArr[octIdx] = 0
66+
octIdx--
67+
}
4568
}
4669

47-
return fmt.Sprintf("Registry A should be %d", initA-1)
70+
final, err := arrayToOct(octArr)
71+
if err != nil {
72+
return fmt.Sprintf("Solved it, but failed to extract number: %v", err)
73+
}
74+
return fmt.Sprintf("Registry A should be %d", final)
4875
}
4976

50-
func compareSeqOut(
51-
m machine,
52-
lenSeq int,
53-
) bool {
54-
if len(m.out) != lenSeq {
55-
return false
77+
func arrayToOct(
78+
arr []int,
79+
) (int64, error) {
80+
strArr := make([]string, len(arr))
81+
for i, n := range arr {
82+
strArr[i] = strconv.Itoa(n)
5683
}
5784

58-
for i, seq := range m.seq {
59-
if m.out[i] != seq {
60-
return false
61-
}
85+
oct, err := strconv.ParseInt(strings.Join(strArr, ""), 8, 64)
86+
if err != nil {
87+
return 0, err
6288
}
63-
64-
return true
89+
return oct, nil
6590
}

0 commit comments

Comments
 (0)