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

Advent of Code 2024

2024/day03.livemd

Advent of Code 2024

Mix.install([
  {:req, "~> 0.3.2"}
])

Day 3

input =
  "https://adventofcode.com/2024/day/3/input"
  |> Req.get!(headers: [cookie: "session=#{System.get_env("AOC_COOKIE")}"])
  |> Map.get(:body)
sample = """
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
"""
defmodule Day3 do
  def parse(input) do
    input
    |> String.trim()
  end
end
import Day3

Part 1

input
|> parse()
|> then(fn line ->
  Regex.scan(~r/mul\((\d{1,3}),(\d{1,3})\)/, line, capture: :all_but_first)
  |> Enum.map(fn [a, b] ->
    [a, b]
    |> Enum.map(&String.to_integer/1)
    |> Enum.product()
  end)
  |> Enum.sum()
end)

Part 2

sample2 = """
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
"""
input
|> parse()
|> then(fn line ->
  Regex.scan(~r/(mul\((\d{1,3}),(\d{1,3})\)|don't\(\)|do\(\))/, line, capture: :all_but_first)
  |> Enum.reduce({0, :do}, fn
    ["do()"], {sum, :dont} ->
      {sum, :do}

    ["don't()"], {sum, :do} ->
      {sum, :dont}

    [_, a, b], {sum, :do} ->
      product =
        [a, b]
        |> Enum.map(&String.to_integer/1)
        |> Enum.product()

      {sum + product, :do}

    _, acc ->
      acc
  end)
  |> elem(0)
end)