-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday07.odin
98 lines (85 loc) · 1.81 KB
/
day07.odin
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
96
97
98
package day07
import "core:fmt"
import "core:os"
import "core:slice"
import "core:strconv"
import "core:strings"
main :: proc() {
content, ok := os.read_entire_file("input/day07.txt")
if !ok {
// could not read file
return
}
defer delete(content)
lines := strings.split_lines(string(content))
equations := make([]Equation, len(lines))
for line, i in lines {
parts := strings.split(line, ": ")
equations[i] = Equation {
strconv.atoi(parts[0]),
slice.mapper(
strings.split(parts[1], " "),
proc(s: string) -> int {return strconv.atoi(s)},
),
}
}
// Part 1
fmt.println(calibration_result(equations, false))
// Part 2
fmt.println(calibration_result(equations, true))
}
Equation :: struct {
result: int,
operands: []int,
}
calibration_result :: proc(equations: []Equation, allow_concat: bool = false) -> int {
result := 0
for equation in equations {
if is_solvable(
equation.result,
equation.operands[0],
equation.operands[1:],
allow_concat,
) {
result += equation.result
}
}
return result
}
is_solvable :: proc(
expected_result: int,
current_result: int,
remaining_operands: []int,
allow_concat: bool,
) -> bool {
if len(remaining_operands) == 0 {
return expected_result == current_result
}
if is_solvable(
expected_result,
current_result + remaining_operands[0],
remaining_operands[1:],
allow_concat,
) {
return true
} else if is_solvable(
expected_result,
current_result * remaining_operands[0],
remaining_operands[1:],
allow_concat,
) {
return true
} else if allow_concat {
return is_solvable(
expected_result,
int_concat(current_result, remaining_operands[0]),
remaining_operands[1:],
allow_concat,
)
} else {
return false
}
}
int_concat :: proc(i1: int, i2: int) -> int {
return strconv.atoi(fmt.aprintf("%d%d", i1, i2))
}