-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
69 lines (58 loc) · 1.33 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
package main
import (
"fmt"
aoc "github.com/shraddhaag/aoc/library"
)
func main() {
input := aoc.ReadFileLineByLine("input.txt")
ans1, ans2 := ans(input)
fmt.Println("answer for part 1: ", ans1)
fmt.Println("answer for part 2: ", ans2)
}
func ans(input []string) (int, int) {
ans1, ans2 := 0, 0
for _, row := range input {
nums := aoc.FetchSliceOfIntsInString(row)
if isCalculationAMatch(nums[0], 0, nums[1:], false) {
ans1 += nums[0]
}
if isCalculationAMatch(nums[0], 0, nums[1:], true) {
ans2 += nums[0]
}
}
return ans1, ans2
}
func calculate(a, b int, operation byte) int {
calculation := 0
switch operation {
case '+':
calculation = a + b
case '*':
calculation = a * b
case '|':
mul, q := 10, 10
for q != 0 {
q = b / mul
if q > 0 {
mul *= 10
}
}
calculation = (a * mul) + b
}
return calculation
}
func isCalculationAMatch(expectedSum, sum int, input []int, isPart2 bool) bool {
if len(input) == 0 {
return sum == expectedSum
}
if sum > expectedSum {
return false
}
if isCalculationAMatch(expectedSum, calculate(sum, input[0], '+'), input[1:], isPart2) {
return true
}
if isPart2 && isCalculationAMatch(expectedSum, calculate(sum, input[0], '|'), input[1:], isPart2) {
return true
}
return isCalculationAMatch(expectedSum, calculate(sum, input[0], '*'), input[1:], isPart2)
}