refactor: Improve X-MAS pattern detection with simplified diagonal checks

This commit is contained in:
Ruidy (aider) 2024-12-04 13:37:52 +01:00
parent 08a41a4b6e
commit 1d6fdd25a8
No known key found for this signature in database
GPG key ID: E00F51288CB857CC

View file

@ -105,41 +105,48 @@ defmodule AdventCode2024.Solutions.Day04 do
end end
defp is_x_mas_pattern?(grid, {row, col}) do defp is_x_mas_pattern?(grid, {row, col}) do
# Define the four possible X patterns (clockwise from top-left) # Get the center character first
patterns = [ center = get_char(grid, row, col)
# Top-left to bottom-right + Top-right to bottom-left if center != "A", do: false,
[{-1, -1}, {0, 0}, {1, 1}, {-1, 1}, {0, 0}, {1, -1}], else: check_diagonals(grid, row, col)
# Top-right to bottom-left + Top-left to bottom-right end
[{-1, 1}, {0, 0}, {1, -1}, {-1, -1}, {0, 0}, {1, 1}],
# Bottom-right to top-left + Bottom-left to top-right defp check_diagonals(grid, row, col) do
[{1, 1}, {0, 0}, {-1, -1}, {1, -1}, {0, 0}, {-1, 1}], # Define the four diagonal directions from center
# Bottom-left to top-right + Bottom-right to top-left diagonals = [
[{1, -1}, {0, 0}, {-1, 1}, {1, 1}, {0, 0}, {-1, -1}] [{-1, -1}, {1, 1}], # top-left to bottom-right
[{-1, 1}, {1, -1}], # top-right to bottom-left
] ]
Enum.any?(patterns, fn pattern -> # For each diagonal pair, check if either forms a valid MAS pattern
check_x_pattern?(grid, {row, col}, pattern) Enum.any?(diagonals, fn [d1, d2] ->
end) chars1 = get_diagonal_chars(grid, row, col, d1)
end chars2 = get_diagonal_chars(grid, row, col, d2)
defp check_x_pattern?(grid, {center_row, center_col}, positions) do case {chars1, chars2} do
letters = positions {[c1, "A", c3], [c4, "A", c6]} when not is_nil(c1) and not is_nil(c3) and not is_nil(c4) and not is_nil(c6) ->
|> Enum.map(fn {dr, dc} -> (is_mas?(c1, c3) and is_mas?(c4, c6)) or
r = center_row + dr (is_mas?(c3, c1) and is_mas?(c6, c4))
c = center_col + dc _ -> false
if within_bounds?(grid, r, c) do
Enum.at(Enum.at(grid, r), c)
end end
end) end)
end
case letters do defp get_diagonal_chars(grid, row, col, {dr, dc}) do
[m1, a1, s1, m2, a2, s2] when not is_nil(m1) and not is_nil(s1) and not is_nil(m2) and not is_nil(s2) -> [
# Check if we have valid MAS patterns in both diagonals get_char(grid, row - dr, col - dc),
(m1 == "M" and a1 == "A" and s1 == "S" and get_char(grid, row, col),
m2 == "M" and a2 == "A" and s2 == "S") or get_char(grid, row + dr, col + dc)
(s1 == "S" and a1 == "A" and m1 == "M" and ]
s2 == "S" and a2 == "A" and m2 == "M") end
_ -> false
defp get_char(grid, row, col) do
if within_bounds?(grid, row, col) do
Enum.at(Enum.at(grid, row), col)
end end
end end
defp is_mas?(first, last) do
first == "M" and last == "S"
end
end end