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

Day 03

day03.livemd

Day 03

Mix.install([
  {:kino, "~> 0.14.2"}
])

IEx.Helpers.c("/Users/johnb/dev/2024adventOfCode/advent_of_code.ex")
alias AdventOfCode, as: AOC
alias Kino.Input

# Note: when making the next template, something like this works well:
#   `cat day04.livemd | sed 's/03/04/' > day04.livemd`
#

Installation and Data

input_p1example = Kino.Input.textarea("Example Data")
input_p1puzzleInput = Kino.Input.textarea("Puzzle Input")
input_source_select =
  Kino.Input.select("Source", [{:example, "example"}, {:puzzle_input, "puzzle input"}])
p1data = fn ->
  (Kino.Input.read(input_source_select) == :example &&
     Kino.Input.read(input_p1example)) ||
    Kino.Input.read(input_p1puzzleInput)
end

Solution

# When inspecting lists of numbers, use "charlists: :as_lists"
defmodule Day03 do
  @parser ~r/mul\((\d{1,3}),(\d{1,3})\)/
  def solve1(text) do
    matches = Regex.scan(@parser, text)
    Enum.reduce(matches, 0, fn match, acc ->
      [_, n1, n2] = match
      acc + String.to_integer(n1) * String.to_integer(n2)
    end)
  end

  @parser2 ~r/mul\((\d{1,3}),(\d{1,3})\)|do\(\)|don't\(\)/
  def solve2(text) do
    Regex.scan(@parser2, text)
    |> Enum.reduce({0, true}, fn match, {acc, doing?} ->
      cond do
        match == ["don't()"] -> {acc, false}
        match == ["do()"] -> {acc, true}
        doing? == true ->
          [_, n1, n2] = match
          {acc + String.to_integer(n1) * String.to_integer(n2), true}
        true -> {acc, false}
      end
    end)
  end
end

# Example:
# xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))

p1data.()
|> Day03.solve1()
|> IO.inspect(label: "\n*** Part 1 solution (example: 161)")
# 183788984

p1data.()
|> Day03.solve2()
|> IO.inspect(label: "\n*** Part 2 solution (example: 48)")
# 62098619