-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
97 lines (79 loc) · 1.4 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
package main
import (
"fmt"
"log"
"strconv"
"github.com/devkvlt/aoc"
)
type char interface {
rune | byte
}
func isDigit[T char](c T) bool {
return '0' <= c && c <= '9'
}
func isSymbol[T char](c T) bool {
return c != '.' && !isDigit(c)
}
func capture(line string, j int) int {
str := string(line[j])
for k := j + 1; k < len(line); k++ {
c := line[k]
if !isDigit(c) {
break
}
str = str + string(c)
}
for k := j - 1; k >= 0; k-- {
c := line[k]
if !isDigit(c) {
break
}
str = string(c) + str
}
num, err := strconv.Atoi(str)
if err != nil {
log.Fatal(err)
}
return num
}
func main() {
lines := aoc.Lines("input")
// Part 1
sum := 0
for i, line := range lines {
for j, c := range line {
if isSymbol(c) {
for k := i - 1; k <= i+1; k++ {
for l := j - 1; l <= j+1; l++ {
if isDigit(lines[k][l]) && (l == j-1 || !isDigit(lines[k][l-1])) {
sum += capture(lines[k], l)
}
}
}
}
}
}
fmt.Println(sum)
// Part 2
sum2 := 0
for i, line := range lines {
for j, c := range line {
if c == '*' {
ratio := 1
count := 0
for k := i - 1; k <= i+1; k++ {
for l := j - 1; l <= j+1; l++ {
if isDigit(lines[k][l]) && (l == j-1 || !isDigit(lines[k][l-1])) && count < 2 {
ratio *= capture(lines[k], l)
count++
}
}
}
if count == 2 {
sum2 += ratio
}
}
}
}
fmt.Println(sum2)
}