Skip to content

Commit 87189c3

Browse files
committed
refac(angch/2024-07): improve value caching and early exit logic in day7 function
1 parent f24f338 commit 87189c3

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

angch/2024-07/main.go

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,50 +29,62 @@ func day7(file string) (part1, part2 int) {
2929
n = append(n, nums)
3030
}
3131
ops := make([]int, len(n)-1)
32+
prevvalues := make([]int, len(n))
33+
prevvalues[0] = n[0]
34+
last := 1
3235
a:
3336
for {
34-
start := n[0]
35-
ispart2 := false
37+
start := prevvalues[last-1]
3638
bad := len(ops) - 1
37-
for i := 1; i < len(n); i++ {
39+
for i := last; i < len(n); i++ {
3840
if ops[i-1] == 0 {
3941
start += n[i]
4042
} else if ops[i-1] == 1 {
4143
start *= n[i]
4244
} else {
43-
ispart2 = true
45+
// ispart2 = true
4446
for range len(rs[i]) {
4547
start *= 10
4648
}
4749
start += n[i]
4850
}
51+
prevvalues[i] = start
4952
if start > testv {
50-
// Early exit
53+
// Early exit, so we know all operators
54+
// after this is "bad", jump to the next
55+
// op.
5156
bad = i - 1
5257
break
5358
}
5459
}
5560
if start == testv {
56-
if ispart2 {
57-
part2 += testv
58-
} else {
59-
part1 += testv
61+
// Need to recheck, since we cached old values, unsure
62+
// if we're using part2 ops or not
63+
for _, v := range ops {
64+
if v == 2 {
65+
part2 += testv
66+
break a
67+
}
6068
}
69+
part1 += testv
6170
break a
6271
}
6372

73+
// Iterate to the next ops, starting with the
74+
// one we know it's bad, no need to test everything
6475
for i := bad; i >= 0; i-- {
6576
ops[i]++
6677
if ops[i] == 3 {
6778
ops[i] = 0
6879
} else {
80+
// Remember where we're continuing, don't
81+
// need to recalc everything
82+
last = i + 1
6983
continue a
7084
}
7185
}
7286
break
7387
}
74-
75-
// log.Println(testv, n)
7688
}
7789
part2 += part1
7890
return

0 commit comments

Comments
 (0)