-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
127 lines (100 loc) · 2.23 KB
/
main.go
File metadata and controls
127 lines (100 loc) · 2.23 KB
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
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 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 solve(grid Grid) int {
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...)
}
partNums := lib.Map(partNumbers.Items(), Cell.num)
return lib.SumSlice(partNums)
}
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..", 4361)
solver.Incorrect(326862) // duplicate numbers were being combined in the partNumbers map, fixed by adding row and col to Cell struct
solver.Verify(517021)
}