-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
95 lines (87 loc) · 1.61 KB
/
main.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"strconv"
"strings"
"github.com/devkvlt/aoc"
)
type Equation struct {
val int
nums []int
}
var equations []Equation
func init() {
lines := aoc.Lines("input")
n := len(lines)
equations = make([]Equation, n)
for i := 0; i < n; i++ {
parts := strings.Split(lines[i], ": ")
nums := strings.Fields(parts[1])
equations[i].val = aoc.Atoi(parts[0])
equations[i].nums = make([]int, len(nums))
for j, num := range nums {
equations[i].nums[j] = aoc.Atoi(num)
}
}
}
func part1() {
var possible func(int, []int) bool
possible = func(val int, nums []int) bool {
n := len(nums)
x := nums[n-1]
if n == 1 {
return val == x
}
var a, b bool
if val > x {
a = possible(val-x, nums[:n-1])
}
if val%x == 0 {
b = possible(val/x, nums[:n-1])
}
return a || b
}
sum := 0
for _, eq := range equations {
if possible(eq.val, eq.nums) {
sum += eq.val
}
}
fmt.Println(sum)
}
func part2() {
var possible func(int, []int) bool
possible = func(val int, nums []int) bool {
n := len(nums)
x := nums[n-1]
if n == 1 {
return val == x
}
var a, b, c bool
if val > x {
a = possible(val-x, nums[:n-1])
}
if val%x == 0 {
b = possible(val/x, nums[:n-1])
}
x_ := strconv.Itoa(x)
val_ := strconv.Itoa(val)
m := len(val_) - len(x_)
if m >= 0 && val_[m:] == x_ {
sub := val_[:m]
c = sub != "" && possible(aoc.Atoi(sub), nums[:n-1])
}
return a || b || c
}
sum := 0
for _, eq := range equations {
if possible(eq.val, eq.nums) {
sum += eq.val
}
}
fmt.Println(sum)
}
func main() {
part1() // 3312271365652
part2() // 509463489296712
}