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

Day 3: Mull It Over

2024/day_03.livemd

Day 3: Mull It Over

Mix.install([:kino])

input = Kino.Input.textarea("Please paste your input:")

Part 1

Run in Livebook

https://adventofcode.com/2024/day/3

data =
  input
  |> Kino.Input.read()
parse_mul_fun = fn str ->
  %{"a" => a, "b" => b} = Regex.named_captures(~r/mul\((?\d+),(?\d+)\)/, str)

  String.to_integer(a) * String.to_integer(b)
end

_answer =
  data
  |> then(&Regex.scan(~r/mul\(\d+,\d+\)/, &1))
  |> List.flatten()
  |> Enum.map(parse_mul_fun)
  |> Enum.sum()

Part 2

https://adventofcode.com/2024/day/3#part2

{answer, _} =
  data
  |> then(&Regex.scan(~r/mul\(\d+,\d+\)|do\(\)|don't\(\)/, &1))
  |> List.flatten()
  |> Enum.reduce({0, _do? = true}, fn command, {acc, do?} ->
    case command do
      "do()" ->
        {acc, true}

      "don't()" ->
        {acc, false}

      "mul" <> _ ->
        case do? do
          true -> {acc + parse_mul_fun.(command), do?}
          false -> {acc, do?}
        end
    end
  end)

answer

9411 Livebook Notebooks