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

Advent 2021 - Day 2

day2.livemd

Advent 2021 - Day 2

Setup

Mix.install([
  {:kino, github: "livebook-dev/kino"}
])
input = Kino.Input.textarea("Please paste your input file:")
input =
  input
  |> Kino.Input.read()
  |> String.trim()
  |> String.split("\n")
  |> Enum.map(fn x ->
    [direction, amount] = String.split(x, " ")
    {String.to_atom(direction), String.to_integer(amount)}
  end)
defmodule Utils do
  def apply_dive(input, acc, callback) do
    list =
      input
      |> Enum.reduce(acc, fn {direction, amount}, previous ->
        callback.(previous, direction, amount)
      end)
      |> Tuple.to_list()

    {horizontal, _} = List.pop_at(list, 0)
    {depth, _} = List.pop_at(list, 1)

    horizontal * depth
  end
end

Part 1

defmodule Part1 do
  def move_part1({previous_horizontal, previous_depth}, :forward, amount) do
    {previous_horizontal + amount, previous_depth}
  end

  def move_part1({previous_horizontal, previous_depth}, :down, amount) do
    {previous_horizontal, previous_depth + amount}
  end

  def move_part1({previous_horizontal, previous_depth}, :up, amount) do
    {previous_horizontal, previous_depth - amount}
  end
end

Utils.apply_dive(input, {0, 0}, &Part1.move_part1/3)

Part 2

defmodule Part2 do
  def move_part2({previous_horizontal, previous_depth, previous_aim}, :down, amount) do
    {previous_horizontal, previous_depth, previous_aim + amount}
  end

  def move_part2({previous_horizontal, previous_depth, previous_aim}, :up, amount) do
    {previous_horizontal, previous_depth, previous_aim - amount}
  end

  def move_part2({previous_horizontal, previous_depth, previous_aim}, :forward, amount) do
    {previous_horizontal + amount, previous_depth + previous_aim * amount, previous_aim}
  end
end

Utils.apply_dive(input, {0, 0, 0}, &Part2.move_part2/3)