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

2022 Day 1

day_01.livemd

2022 Day 1

Mix.install([:kino])

Input

Run in Livebook

input = Kino.Input.textarea("Puzzle Input")

Code

Module

defmodule Calories do
  def greatest(input) do
    input
    |> process_input()
    |> Enum.map(&Enum.sum/1)
    |> Enum.max()
  end

  def top_three(input) do
    input
    |> process_input()
    |> Enum.map(&Enum.sum/1)
    |> Enum.sort()
    |> Enum.take(-3)
    |> Enum.sum()
  end

  defp process_input(input) do
    input
    |> String.split("\n\n")
    |> Enum.map(
      &(&1
        |> String.split()
        |> Enum.map(fn str -> String.to_integer(str) end))
    )
  end
end

Evaluation

part_1 =
  input
  |> Kino.Input.read()
  |> Calories.greatest()

part_2 =
  input
  |> Kino.Input.read()
  |> Calories.top_three()

{part_1, part_2}

Test

ExUnit.start(autorun: false)

defmodule CaloriesTest do
  use ExUnit.Case, async: true

  setup do
    input = ~s(
1000
2000
3000

4000

5000
6000

7000
8000
9000

10000
)

    {:ok, input: input}
  end

  test "greatest", %{input: input} do
    assert Calories.greatest(input) == 24000
  end

  test "top_three", %{input: input} do
    assert Calories.top_three(input) == 45000
  end
end

ExUnit.run()