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

Day 1

Day1.livemd

Day 1

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

Input

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2023", "1", System.fetch_env!("LB_AOC_SESSION"))

Part 1

puzzle_input
|> String.split("\n")
|> Enum.map(&Regex.replace(~r/\D/, &1, ""))
|> Enum.map(&amp;String.to_integer(String.at(&amp;1, 0) <> String.at(&amp;1, -1)))
|> Enum.sum()

Part 2

defmodule CalibrationCode do
  @digits %{
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4,
    "five" => 5,
    "six" => 6,
    "seven" => 7,
    "eight" => 8,
    "nine" => 9
  }
  @reverse_digits @digits |> Enum.map(fn {k, v} -> {String.reverse(k), v} end) |> Map.new()

  def starting_digit(<> <> _rest, _) when d in ?1..?9, do: d - 48

  def starting_digit(str, digits) do
    digits |> Enum.find_value(fn {k, v} -> if(String.starts_with?(str, k), do: v) end)
  end

  def first_digit(str, digits \\ @digits) do
    starting_digit(str, digits) || String.slice(str, 1..-1) |> first_digit(digits)
  end

  def last_digit(str), do: first_digit(String.reverse(str), @reverse_digits)

  def parse(str), do: 10 * first_digit(str) + last_digit(str)
end

lines
|> Enum.map(&amp;CalibrationCode.parse/1)
|> Enum.sum()