-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.go
65 lines (55 loc) · 1.18 KB
/
part2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package day07
import (
"math"
"strconv"
"strings"
"github.com/patrick22414/Advent-of-Code-2024/readinput"
)
func isEquationPossible3(n int, ns []int, target int) bool {
if len(ns) == 0 {
return n == target
}
if len(ns) == 1 {
return n+ns[0] == target ||
n*ns[0] == target ||
concat(n, ns[0]) == target
}
// then len(ns) > 1
if n >= target {
return false
}
return isEquationPossible3(n+ns[0], ns[1:], target) ||
isEquationPossible3(n*ns[0], ns[1:], target) ||
isEquationPossible3(concat(n, ns[0]), ns[1:], target)
}
func concat(x, y int) int {
return x*int(math.Pow10(int(math.Log10(float64(y)))+1)) + y
}
func Part2() int {
total := 0
for line := range readinput.ReadInput("./input.txt") {
res, operands, ok := strings.Cut(line, ": ")
if !ok {
panic("")
}
target, err := strconv.Atoi(res)
if err != nil {
panic(err)
}
ns := make([]int, 0)
for _, t := range strings.Split(operands, " ") {
n, err := strconv.Atoi(t)
if err != nil {
panic(err)
}
ns = append(ns, n)
}
if isEquationPossible3(ns[0], ns[1:], target) {
// fmt.Println(line, true)
total += target
} else {
// fmt.Println(line, false)
}
}
return total
}