Day 4: Ceres Search

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • aurele@sh.itjust.works
    link
    fedilink
    arrow-up
    1
    ·
    21 days ago

    Elixir

    defmodule AdventOfCode.Solution.Year2024.Day04 do
      use AdventOfCode.Solution.SharedParse
    
      defmodule Map do
        defstruct [:chars, :width, :height]
      end
    
      @impl true
      def parse(input) do
        chars = String.split(input, "\n", trim: true) |> Enum.map(&String.codepoints/1)
        %Map{chars: chars, width: length(Enum.at(chars, 0)), height: length(chars)}
      end
    
      def at(%Map{} = map, x, y) do
        cond do
          x < 0 or x >= map.width or y < 0 or y >= map.height -> ""
          true -> map.chars |> Enum.at(y, []) |> Enum.at(x, "")
        end
      end
    
      def part1(map) do
        dirs = for dx <- -1..1, dy <- -1..1, {dx, dy} != {0, 0}, do: {dx, dy}
        xmas = String.codepoints("XMAS") |> Enum.with_index() |> Enum.drop(1)
    
        for x <- 0..(map.width - 1),
            y <- 0..(map.height - 1),
            "X" == at(map, x, y),
            {dx, dy} <- dirs,
            xmas
            |> Enum.all?(fn {c, n} -> at(map, x + dx * n, y + dy * n) == c end),
            reduce: 0 do
          t -> t + 1
        end
      end
    
      def part2(map) do
        for x <- 0..(map.width - 1),
            y <- 0..(map.height - 1),
            "A" == at(map, x, y),
            (at(map, x - 1, y - 1) <> at(map, x + 1, y + 1)) in ["MS", "SM"],
            (at(map, x - 1, y + 1) <> at(map, x + 1, y - 1)) in ["MS", "SM"],
            reduce: 0 do
          t -> t + 1
        end
      end
    end