-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
146 lines (113 loc) · 2.57 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package main
import (
"bytes"
"github.com/danvolchek/AdventOfCode/lib"
)
type Grid struct {
lib.MapGrid[Cell]
symbols []Cell
}
type Cell struct {
number int
symbol string
pos lib.Pos
}
func (c Cell) isNum() bool {
return c.number != 0
}
func (c Cell) num() int {
return c.number
}
func (c Cell) isGear() bool {
return c.symbol == "*"
}
func parse(input []byte) Grid {
cells := make(map[int]map[int]Cell)
var symbols []Cell
set := func(row, col int, cell Cell) {
rowCells, ok := cells[row]
if !ok {
rowCells = make(map[int]Cell)
cells[row] = rowCells
}
rowCells[col] = cell
}
rows := bytes.Split(bytes.TrimSpace(input), []byte{'\n'})
for row, line := range rows {
for col := 0; col < len(line); col++ {
char := line[col]
if char == '.' {
continue
}
if !lib.IsDigit(char) {
symbol := Cell{
symbol: string(char),
pos: lib.Pos{
Row: row,
Col: col,
},
}
set(row, col, symbol)
symbols = append(symbols, symbol)
continue
}
digitIndex := col
var digits string
for {
if digitIndex == len(line) || !lib.IsDigit(line[digitIndex]) {
break
}
digits += string(line[digitIndex])
digitIndex++
}
cell := Cell{
number: lib.Atoi(digits),
pos: lib.Pos{
Row: row,
Col: col,
},
}
for i := col; i < digitIndex; i++ {
set(row, i, cell)
}
col += len(digits) - 1
}
}
return Grid{
MapGrid: lib.MapGrid[Cell]{
Rows: len(rows),
Cols: len(rows[0]),
Grid: cells,
},
symbols: symbols,
}
}
func getPartNumbers(grid Grid) lib.Set[Cell] {
var partNumbers lib.Set[Cell]
for _, symbol := range grid.symbols {
adjacentCells := lib.Adjacent[Cell](symbol.pos, grid, true)
adjacentPartNumbers := lib.Filter(adjacentCells, Cell.isNum)
partNumbers.Add(adjacentPartNumbers...)
}
return partNumbers
}
func solve(grid Grid) int {
var gearRatios []int
partNumbers := getPartNumbers(grid)
for _, gear := range lib.Filter(grid.symbols, Cell.isGear) {
adjacentCells := lib.Adjacent[Cell](gear.pos, grid, true)
adjacentPartNumbers := lib.Unique(lib.Filter(adjacentCells, partNumbers.Contains))
if len(adjacentPartNumbers) == 2 {
gearRatios = append(gearRatios, lib.MulSlice(lib.Map(adjacentPartNumbers, Cell.num)))
}
}
return lib.SumSlice(gearRatios)
}
func main() {
solver := lib.Solver[Grid, int]{
ParseF: lib.ParseBytesFunc(parse),
SolveF: solve,
}
solver.Expect("467..114..\n...*......\n..35..633.\n......#...\n617*......\n.....+.58.\n..592.....\n......755.\n...$.*....\n.664.598..", 467835)
solver.Verify(81296995)
}