aoc2024/day-04/internal/one/solve.go
2024-12-06 19:57:07 +00:00

56 lines
1018 B
Go

package one
import (
"bytes"
"github.com/onyx-and-iris/aoc2024/day-04/internal/util"
log "github.com/sirupsen/logrus"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
lines, err := util.ReadLines(r)
if err != nil {
return 0, err
}
var sum int
for i := 0; i < len(lines); i++ {
for j := 0; j < len(lines[i]); j++ {
neighbours := newNeighbours(j, i)
for _, n := range neighbours.all() {
if n.x < 0 || n.y < 0 || n.y >= len(lines) || n.x >= len(lines[i]) {
continue
}
if lines[i][j] == 'X' {
if checkNeighbours(n, "MAS", lines) {
sum++
}
}
}
}
}
return sum, nil
}
func checkNeighbours(n neighbour, word string, lines []string) bool {
if len(word) == 0 {
log.Debug("we found a full XMAS")
return true
}
if n.x < 0 || n.y < 0 || n.y >= len(lines) || n.x >= len(lines[n.y]) {
return false
}
if lines[n.y][n.x] != word[0] {
return false
}
return checkNeighbours(newNeighbour(n.direction, n.x, n.y), word[1:], lines)
}