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

Advent of Code - Day 1

elixir-livebook/day1.livemd

Advent of Code - Day 1

Mix.install([
  {:kino_aoc, "~> 0.1"},
  # {:benchee, "~> 1.0", only: :dev}
  {:kino_benchee, github: "akoutmos/kino_benchee", branch: "initial_release_prep"}
])

Introduction

Day 1: Trebuchet?!

https://adventofcode.com/2023/day/1

Description

Part One

Something is wrong with global snow production, and you’ve been selected to take a look. The Elves have even given you a map; on it, they’ve used stars to mark the top fifty locations that are likely to be having problems.

You’ve been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th.

Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!

You try to ask why they can’t just use a weather machine (“not powerful enough”) and where they’re even sending you (“the sky”) and why your map looks mostly blank (“you sure ask a lot of questions”) and hang on did you just say the sky (“of course, where do you think snow comes from”) when you realize that the Elves are already loading you into a trebuchet (“please hold still, we need to strap you in”).

As they’re making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document.

The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.

For example:

1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet

In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.

Consider your entire calibration document. What is the sum of all of the calibration values?

Part Two

Your calculation isn’t quite right. It looks like some of the digits are actually spelled out with letters: one, two, three, four, five, six, seven, eight, and nine also count as valid “digits”.

Equipped with this new information, you now need to find the real first and last digit on each line. For example:

two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen

In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.

What is the sum of all of the calibration values?

Puzzle

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

Parser

Code - Parser

defmodule Parser do
  @numbers [
    "oneight",
    "twone",
    "threeight",
    "fiveight",
    "sevenine",
    "eightwo",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine"
  ]

  def parse_with_numbers(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(fn line ->
      line
      |> String.replace(@numbers, fn
        "oneight" -> "18"
        "twone" -> "21"
        "threeight" -> "38"
        "fiveight" -> "58"
        "sevenine" -> "79"
        "eightwo" -> "82"
        "one" -> "1"
        "two" -> "2"
        "three" -> "3"
        "four" -> "4"
        "five" -> "5"
        "six" -> "6"
        "seven" -> "7"
        "eight" -> "8"
        "nine" -> "9"
      end)
      |> String.codepoints()
      |> Enum.filter(&amp;("0" <= &amp;1 and &amp;1 <= "9"))
      |> Enum.map(&amp;String.to_integer/1)
    end)
  end

  def parse(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(fn line ->
      line
      |> String.codepoints()
      |> Enum.filter(&amp;("0" <= &amp;1 and &amp;1 <= "9"))
      |> Enum.map(&amp;String.to_integer/1)
    end)
  end
end

Tests - Parser

ExUnit.start(autorun: false)

defmodule ParserTest do
  use ExUnit.Case, async: true
  import Parser

  @input """
  1abc2
  pqr3stu8vwx
  a1b2c3d4e5f
  treb7uchet
  """
  @expected [[1, 2], [3, 8], [1, 2, 3, 4, 5], [7]]

  test "parse test" do
    actual = parse(@input)
    assert actual == @expected
  end
end

ExUnit.run()

Part One

Code - Part 1

defmodule PartOne do
  def solve(input) do
    IO.puts("--- Part One ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    input
    |> Parser.parse()
    |> Enum.map(&amp;get_calibration_values/1)
    |> Enum.sum()
  end

  def get_calibration_values([a]), do: a * 10 + a

  def get_calibration_values([a | tail]) do
    a * 10 + hd(Enum.reverse(tail))
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

defmodule PartOneTest do
  use ExUnit.Case, async: true
  import PartOne

  @input """
  1abc2
  pqr3stu8vwx
  a1b2c3d4e5f
  treb7uchet
  """
  @expected 142

  test "part one" do
    actual = run(@input)
    assert actual == @expected
  end
end

ExUnit.run()

Solution - Part 1

PartOne.solve(puzzle_input)

Part Two

Code - Part 2

defmodule PartTwo do
  def solve(input) do
    IO.puts("--- Part Two ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    input
    |> Parser.parse_with_numbers()
    |> Enum.map(&amp;get_calibration_values/1)
    |> Enum.sum()
  end

  def get_calibration_values([a]), do: a * 10 + a

  def get_calibration_values([a | tail]) do
    a * 10 + hd(Enum.reverse(tail))
  end
end

Tests - Part 2

ExUnit.start(autorun: false)

defmodule PartTwoTest do
  use ExUnit.Case, async: true
  import PartTwo

  @input """
  two1nine
  eightwothree
  abcone2threexyz
  xtwone3four
  4nineeightseven2
  zoneight234
  7pqrstsixteen
  """
  @expected 281

  test "part two" do
    actual = run(@input)
    assert actual == @expected
  end
end

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input)

Benchmarking

defmodule Benchmarks do
  def part1(input) do
    PartOne.run(input)
  end

  def part2(input) do
    PartTwo.run(input)
  end
end

Benchee.run(
  %{
    "day01.part1" => &amp;Benchmarks.part1/1,
    "day01.part2" => &amp;Benchmarks.part2/1
  },
  inputs: %{
    "puzzle" => puzzle_input
  },
  time: 1,
  memory_time: 1,
  reduction_time: 1
)