Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 4

2024/day04.livemd

Day 4

Mix.install([{:utils, path: "#{__DIR__}/utils"}])

Solution

lookup =
  Utils.read_grid("day04")
  |> then(fn {grid, _} -> grid end)
  |> Enum.group_by(fn {_, key} -> key end, fn {coords, _} -> coords end)
  |> Enum.into(%{}, fn {k, v} -> {k, MapSet.new(v)} end)
for {x, y} <- Map.get(lookup, ?X), dx <- -1..1, dy <- -1..1 do
  found? = fn key, dist -> {x + dist * dx, y + dist * dy} in Map.get(lookup, key) end
  found?.(?M, 1) and found?.(?A, 2) and found?.(?S, 3)
end
|> Enum.count(&amp; &amp;1)
for {x, y} <- Map.get(lookup, ?M), sign <- [-1, 1], vertical <- [false, true] do
  found? = fn key, {delx, dely} ->
    {dx, dy} = if vertical, do: {delx, dely}, else: {-dely, delx}
    {x + sign * dx, y + sign * dy} in Map.get(lookup, key)
  end

  found?.(?M, {2, 0}) and found?.(?A, {1, 1}) and found?.(?S, {0, 2}) and found?.(?S, {2, 2})
end
|> Enum.count(&amp; &amp;1)