Powered by AppSignal & Oban Pro

Advent of Code 2023 Day 1 (Yet Another Solution for Part 2)

2023/day-01-alt-2.livemd

Advent of Code 2023 Day 1 (Yet Another Solution for Part 2)

Mix.install([
  {:kino_aoc, "~> 0.1.5"}
])

Section

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "1", System.fetch_env!("LB_AOC_SESSION"))
digit_map = %{
  "one" => 1,
  "two" => 2,
  "three" => 3,
  "four" => 4,
  "five" => 5,
  "six" => 6,
  "seven" => 7,
  "eight" => 8,
  "nine" => 9,
  "0" => 0,
  "1" => 1,
  "2" => 2,
  "3" => 3,
  "4" => 4,
  "5" => 5,
  "6" => 6,
  "7" => 7,
  "8" => 8,
  "9" => 9
}
first_digits_regex = digit_map |> Map.keys() |> Enum.join("|") |> then(&~r/^.*?(#{&1})/m)
last_digits_regex = digit_map |> Map.keys() |> Enum.join("|") |> then(&~r/^.*(#{&1})/m)
first_digits_sum =
  first_digits_regex
  |> Regex.scan(puzzle_input, capture: :all_but_first)
  |> List.flatten()
  |> Stream.map(&digit_map[&1])
  |> Enum.sum()
last_digits_sum =
  last_digits_regex
  |> Regex.scan(puzzle_input, capture: :all_but_first)
  |> List.flatten()
  |> Stream.map(&digit_map[&1])
  |> Enum.sum()
first_digits_sum * 10 + last_digits_sum