fix: Correct MASAS pattern detection in Day04 grid search

fix: Refactor X-MAS pattern detection in Day04 solution

fix: Remove extra `end` in day4.ex module
This commit is contained in:
Ruidy (aider) 2024-12-04 13:32:59 +01:00 committed by Ruidy
parent bacce02f21
commit 998b6f6405
No known key found for this signature in database
GPG key ID: E00F51288CB857CC

View file

@ -98,7 +98,7 @@ defmodule AdventCode2024.Solutions.Day04 do
] ]
grid_chars = Enum.map(grid, &String.graphemes/1) grid_chars = Enum.map(grid, &String.graphemes/1)
grid_chars grid_chars
|> Enum.with_index() |> Enum.with_index()
|> Enum.reduce(0, fn {row, row_idx}, acc -> |> Enum.reduce(0, fn {row, row_idx}, acc ->
@ -122,24 +122,41 @@ defmodule AdventCode2024.Solutions.Day04 do
end end
defp find_xmas?(grid, {row, col}, {d_row, d_col}) do defp find_xmas?(grid, {row, col}, {d_row, d_col}) do
# Define the positions for the X shape # Define the positions for the X pattern
positions = [ positions_right = [
# M
{row, col}, {row, col},
# A
{row + d_row, col + d_col}, {row + d_row, col + d_col},
{row + 2 * d_row, col + 2 * d_col}, # S
{row + d_row, col - d_col} {row + 2 * d_row, col + 2 * d_col}
] ]
# Check if all positions contain the correct letters for "MAS" positions_left = [
Enum.with_index(positions) # M
|> Enum.all?(fn {{r, c}, idx} -> {row, col + 2 * d_col},
within_bounds?(grid, r, c) && # A (center shared)
case idx do {row + d_row, col + d_col},
0 -> Enum.at(Enum.at(grid, r), c) == "M" # S
1 -> Enum.at(Enum.at(grid, r), c) == "A" {row + 2 * d_row, col}
2 -> Enum.at(Enum.at(grid, r), c) == "S" ]
3 -> Enum.at(Enum.at(grid, r), c) == "S"
end # Check both diagonals for "MAS" (can be forwards or backwards)
end) (check_mas?(grid, positions_right) or check_sam?(grid, positions_right)) and
(check_mas?(grid, positions_left) or check_sam?(grid, positions_left))
end
defp check_mas?(grid, [{r1, c1}, {r2, c2}, {r3, c3}]) do
within_bounds?(grid, r1, c1) and within_bounds?(grid, r2, c2) and within_bounds?(grid, r3, c3) and
Enum.at(Enum.at(grid, r1), c1) == "M" and
Enum.at(Enum.at(grid, r2), c2) == "A" and
Enum.at(Enum.at(grid, r3), c3) == "S"
end
defp check_sam?(grid, [{r1, c1}, {r2, c2}, {r3, c3}]) do
within_bounds?(grid, r1, c1) and within_bounds?(grid, r2, c2) and within_bounds?(grid, r3, c3) and
Enum.at(Enum.at(grid, r1), c1) == "S" and
Enum.at(Enum.at(grid, r2), c2) == "A" and
Enum.at(Enum.at(grid, r3), c3) == "M"
end end
end end