-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
76 lines (62 loc) · 1.46 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
package main
import (
"fmt"
"io"
"github.com/teivah/go-aoc"
)
func fs1(input io.Reader) int {
res := 0
for _, line := range aoc.ReaderToStrings(input) {
target, numbers := parse(line)
if solvable1(target, 0, numbers) {
res += target
}
}
return res
}
func solvable1(target, current int, numbers []int) bool {
if current == 0 {
return solvable1(target, numbers[0], numbers[1:])
}
if len(numbers) == 0 {
return target == current
}
if current > target {
return false
}
return solvable1(target, current+numbers[0], numbers[1:]) ||
solvable1(target, current*numbers[0], numbers[1:])
}
func parse(s string) (int, []int) {
del := aoc.NewDelimiter(s, ": ")
target := del.GetInt(0)
del = aoc.NewDelimiter(del.GetString(1), " ")
return target, del.GetInts()
}
func fs2(input io.Reader) int {
res := 0
for _, line := range aoc.ReaderToStrings(input) {
target, numbers := parse(line)
if solvable2(target, 0, numbers) {
res += target
}
}
return res
}
func solvable2(target, current int, numbers []int) bool {
if current == 0 {
return solvable2(target, numbers[0], numbers[1:])
}
if len(numbers) == 0 {
return target == current
}
if current > target {
return false
}
return solvable2(target, current+numbers[0], numbers[1:]) ||
solvable2(target, current*numbers[0], numbers[1:]) ||
solvable2(target, concatenate(current, numbers[0]), numbers[1:])
}
func concatenate(a, b int) int {
return aoc.StringToInt(fmt.Sprintf("%d%d", a, b))
}