Powered by AppSignal & Oban Pro

Advent of Code 2023 - Day 01

2023/01.livemd

Advent of Code 2023 - Day 01

Mix.install([
  {:kino, "~> 0.11.0"},
  {:kino_aoc, github: "ljgago/kino_aoc"}
])

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "1", System.fetch_env!("LB_AOC_SESSION"))
document =
  puzzle_input
  |> String.split("\n")

Part 1

document
|> Stream.map(fn line ->
  matches =
    Regex.scan(~r/\d/, line)
    |> List.flatten()

  first = List.first(matches)
  last = List.last(matches)

  String.to_integer("#{first}#{last}")
end)
|> Enum.sum()

Part 2

pattern = ~r/(?=(\d|one|two|three|four|five|six|seven|eight|nine))/

document
|> Stream.map(fn line ->
  matches =
    Regex.scan(pattern, line, capture: :all_but_first)
    |> List.flatten()
    |> Enum.map(fn
      "one" -> "1"
      "two" -> "2"
      "three" -> "3"
      "four" -> "4"
      "five" -> "5"
      "six" -> "6"
      "seven" -> "7"
      "eight" -> "8"
      "nine" -> "9"
      input -> input
    end)

  first = List.first(matches)
  last = List.last(matches)

  String.to_integer(first <> last)
end)
|> Enum.sum()

Run in Livebook