Advent of Code 2024 - Day 3

Here are the solutions I came up with for today:

Part 1:

defmodule Day3.Part1 do
  def solve() do
    File.stream!("03/input.txt")
    |> Enum.reduce(
      0,
      fn line, acc ->
        acc +
          (~r/mul\((\d{1,3}),(\d{1,3})\)/
           |> Regex.scan(line |> String.trim(), capture: :all_but_first)
           |> Enum.reduce(
             0,
             fn [a, b], acc -> acc + String.to_integer(a) * String.to_integer(b) end
           ))
      end
    )
    |> IO.puts()
  end
end

Day3.Part1.solve()

Part 2:

defmodule Day3.Part2 do
  defp sum_part(part) do
    ~r/mul\((\d{1,3}),(\d{1,3})\)/
    |> Regex.scan(part, capture: :all_but_first)
    |> Enum.reduce(
      0,
      fn [a, b], acc -> acc + String.to_integer(a) * String.to_integer(b) end
    )
  end

  def solve() do
    File.stream!("03/input.txt")
    |> Enum.reduce(
      {0, true},
      fn line, {acc, start_enabled?} ->
        {acc +
           (line
            |> String.trim()
            |> String.split("do")
            |> (fn parts ->
                  if start_enabled? do
                    parts
                  else
                    parts
                    |> Enum.drop(1)
                  end
                end).()
            |> Enum.filter(&(not String.starts_with?(&1, "n't()")))
            |> Enum.map(&sum_part/1)
            |> List.to_tuple()
            |> Tuple.sum()),
         ~r/do\(\)/
         |> Regex.scan(line, capture: :all, return: :index)
         |> List.last()
         |> List.last()
         |> elem(0) >
           ~r/don't\(\)/
           |> Regex.scan(line, capture: :all, return: :index)
           |> List.last()
           |> List.last()
           |> elem(0)}
      end
    )
    |> elem(0)
    |> IO.puts()
  end
end

Day3.Part2.solve()

:wave:

I think there is a topic for day 3 already: Advent of Code 2024 - Day 3

Indeed. Not sure how to delete this topic. I was up last night and posted as soon as I finished. Unfortunately, so did a lot of other people and the other thread popped up while mine was still under admin review.

If an admin sees this, please remove this topic.

Ah, right! Sorry, I forgot about your comment: Advent of Code 2024 - Day 3 - #3 by mwilsoncoding

Seems like Elixir forum experienced a race condition :slight_smile:

1 Like