Skip to content

Commit 7ae6601

Browse files
committed
A little cleanup
1 parent 05460f7 commit 7ae6601

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

day-4/main.go

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,17 @@ func main() {
3737
}
3838
}
3939

40-
const MAS = "MAS"
41-
const XMAS = "X" + MAS
40+
const XMAS = "XMAS"
4241

4342
func part1(input string) int {
4443
parsed := parseInput(input)
44+
grid := Grid{parsed}
4545
foundWords := 0
4646
// start traversing the grid
4747
for y, row := range parsed {
4848
for x := range row {
4949
coord := Coords{x, y}
50-
foundWords += xmasSearch(parsed, "", coord, AllDirections)
50+
foundWords += xmasSearch(grid, "", coord, AllDirections)
5151
}
5252
}
5353

@@ -93,6 +93,10 @@ func (g Grid) CharAt(c Coords) rune {
9393
return rune(g.Data[c.y][c.x])
9494
}
9595

96+
func (g Grid) InBounds(c Coords) bool {
97+
return c.x >= 0 && c.y >= 0 && c.y < len(g.Data) && c.x < len(g.Data[c.y])
98+
}
99+
96100
type Coords struct {
97101
x int
98102
y int
@@ -161,9 +165,9 @@ func (c Coords) Direction(d Direction) Coords {
161165
}
162166
}
163167

164-
func xmasSearch(grid []string, currentWord string, coords Coords, directions []Direction) int {
168+
func xmasSearch(grid Grid, currentWord string, coords Coords, directions []Direction) int {
165169
foundWords := 0
166-
newWord := currentWord + string(grid[coords.y][coords.x])
170+
newWord := currentWord + string(grid.CharAt(coords))
167171
if newWord == XMAS {
168172
// we match!
169173
return 1
@@ -175,7 +179,7 @@ func xmasSearch(grid []string, currentWord string, coords Coords, directions []D
175179
for _, direction := range directions {
176180
newCoord := coords.Direction(direction)
177181
// check for bounds
178-
if newCoord.x >= 0 && newCoord.y >= 0 && newCoord.y < len(grid) && newCoord.x < len(grid[newCoord.y]) {
182+
if grid.InBounds(newCoord) {
179183
foundWords += xmasSearch(grid, newWord, newCoord, []Direction{direction})
180184
}
181185
}

0 commit comments

Comments
 (0)