-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (81 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
_ "embed"
"fmt"
"strconv"
"strings"
)
//go:embed input.txt
var input string
type Line struct {
txt string
checksum []int
possible int
}
func main() {
lines := parse()
sum := 0
for i := range lines {
solve(&lines[i], lines[i].txt)
sum += lines[i].possible
}
fmt.Println("Part 1 =", sum)
}
func solve(line *Line, current string) {
crc := calculateCRC(current)
next := strings.Index(current, "?")
if next == -1 {
if equal(crc, line.checksum) {
line.possible++
}
return
}
solve(line, current[:next]+"."+current[next+1:])
solve(line, current[:next]+"#"+current[next+1:])
}
func calculateCRC(txt string) []int {
checksum := []int{}
count := 0
for _, c := range txt {
if string(c) == "." {
if count > 0 {
checksum = append(checksum, count)
count = 0
}
continue
}
count++
}
if count > 0 {
checksum = append(checksum, count)
count = 0
}
return checksum
}
func parse() []Line {
lines := []Line{}
for _, s := range strings.Split(strings.TrimSpace(input), "\n") {
val := strings.Split(strings.TrimSpace(s), " ")
check := []int{}
for _, n := range strings.Split(val[1], ",") {
num, _ := strconv.Atoi(n)
check = append(check, num)
}
lines = append(lines, Line{
txt: val[0],
checksum: check,
})
}
return lines
}
func equal(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}