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

AoC 2023 Day 1

2023/day1.livemd

AoC 2023 Day 1

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

Input

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

Part 1

puzzle_input
|> String.split("\n")
|> Enum.map(fn line ->
  line
  |> String.codepoints()
  |> Enum.map(&Integer.parse/1)
  |> Enum.reject(&match?(:error, &1))
  |> Enum.map(&elem(&1, 0))
end)
|> Enum.map(fn
  [n] -> {n, n}
  [n, m] -> {n, m}
  [n | list] -> {n, List.last(list)}
end)
|> Enum.map(fn {n, m} ->
  "#{n}#{m}" |> String.to_integer()
end)
|> Enum.sum()

Part 2

defmodule Parser do
  def parse_num(""), do: :end
  def parse_num("zero" <> rest), do: {0, "ero" <> rest}
  def parse_num("one" <> rest), do: {1, "ne" <> rest}
  def parse_num("two" <> rest), do: {2, "wo" <> rest}
  def parse_num("three" <> rest), do: {3, "hree" <> rest}
  def parse_num("four" <> rest), do: {4, "our" <> rest}
  def parse_num("five" <> rest), do: {5, "ive" <> rest}
  def parse_num("six" <> rest), do: {6, "ix" <> rest}
  def parse_num("seven" <> rest), do: {7, "even" <> rest}
  def parse_num("eight" <> rest), do: {8, "ight" <> rest}
  def parse_num("nine" <> rest), do: {9, "ine" <> rest}
  def parse_num("0" <> rest), do: {0, rest}
  def parse_num("1" <> rest), do: {1, rest}
  def parse_num("2" <> rest), do: {2, rest}
  def parse_num("3" <> rest), do: {3, rest}
  def parse_num("4" <> rest), do: {4, rest}
  def parse_num("5" <> rest), do: {5, rest}
  def parse_num("6" <> rest), do: {6, rest}
  def parse_num("7" <> rest), do: {7, rest}
  def parse_num("8" <> rest), do: {8, rest}
  def parse_num("9" <> rest), do: {9, rest}
  def parse_num(<<_::binary-size(1)>> <> rest), do: {:discard, rest}

  def parse_line(line) do
    parse_line(line, [])
  end

  def parse_line(line, acc) do
    line
    |> parse_num()
    |> case do
      :end -> Enum.reverse(acc)
      {:discard, rest} -> parse_line(rest, acc)
      {n, rest} -> parse_line(rest, [n | acc])
    end
  end
end
puzzle_input
|> String.split("\n")
|> Enum.map(&amp;Parser.parse_line/1)
|> Enum.map(fn
  [n] -> {n, n}
  [n, m] -> {n, m}
  [n | list] -> {n, List.last(list)}
end)
|> Enum.map(fn {n, m} ->
  "#{n}#{m}" |> String.to_integer()
end)
|> Enum.sum()