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

Advent of Code 2024 - Day 03

2024/day-03.livemd

Advent of Code 2024 - Day 03

Mix.install([{:kino, github: "livebook-dev/kino"}])

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

Part 1

input = Kino.Input.read(kino_input)

regex = ~r/mul\((\d+),(\d+)\)/

regex
  |> Regex.scan(input)
  |> Enum.map(fn [_, a, b] -> String.to_integer(a) * String.to_integer(b) end)
  |> Enum.sum()

Part 2

input = Kino.Input.read(kino_input)

regex = ~r/mul\((\d+),(\d+)\)|do\(\)|don't\(\)/

regex
  |> Regex.scan(input)
  |> Enum.reduce({true, 0}, fn
    [_, a, b], {enabled, acc} when enabled ->
      {enabled, acc + String.to_integer(a) * String.to_integer(b)}

    ["do()"], {_enabled, acc} ->
      {true, acc}

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

    _, {enabled, acc} ->
      {enabled, acc}
  end)