Skip to content

Commit

Permalink
day 4 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
gamersi committed Dec 4, 2024
1 parent b0a45f3 commit 8c6539b
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
68 changes: 68 additions & 0 deletions day04p1/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package day04p1

import (
"io"

"aoc/utils"
)

func Solve(r io.Reader) any {
lines := utils.ReadLines(r)

grid := make([][]rune, len(lines))

for i, line := range lines {
for _, c := range line {
grid[i] = append(grid[i], c)
}
}

height := len(grid)
width := len(grid[0])

const WORD_TO_FIND = "XMAS"

sum := 0

for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
if grid[y][x] == 'X' {
sum += countWord(grid, x, y, width, height, WORD_TO_FIND)
}
}
}

return sum
}

func countWord(grid [][]rune, x, y, width, height int, word string) int {
directions := [][2]int{
{0, 1},
{1, 0},
{1, 1},
{1, -1},
{-1, 1},
{-1, 0},
{0, -1},
{-1, -1},
}

occurrences := 0

for _, dir := range directions {
dx, dy := dir[0], dir[1]
found := true
for i := 1; i < len(word); i++ {
newX := x + i*dx
newY := y + i*dy
if newX < 0 || newX >= width || newY < 0 || newY >= height || grid[newY][newX] != rune(word[i]) {
found = false
break
}
}
if found {
occurrences++
}
}
return occurrences
}
42 changes: 42 additions & 0 deletions day04p1/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day04p1

import (
"strings"
"testing"

"aoc/utils"
)

var testInput = `MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX`

func TestSolve(t *testing.T) {
tests := []struct {
input string
answer int
}{
{testInput, 18},
}

if testing.Verbose() {
utils.Verbose = true
}

for _, test := range tests {
r := strings.NewReader(test.input)

result := Solve(r).(int)

if result != test.answer {
t.Errorf("Expected %d, got %d", test.answer, result)
}
}
}

0 comments on commit 8c6539b

Please sign in to comment.