this post was submitted on 04 Dec 2024
18 points (95.0% liked)

Advent Of Code

996 readers
4 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

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

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 1 points 1 month 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