Powered by AppSignal & Oban Pro

Day 1 - Advent of Code 2022

lib/advent_of_code/2022/day-01.livemd

Day 1 - Advent of Code 2022

Mix.install([:kino])
:ok

2022 - Day 1: Calorie Counting

Part One: Prompt

The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves’ expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input).

The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they’ve brought with them, one item per line. Each Elf separates their own inventory from the previous Elf’s inventory (if any) by a blank line.

For example, suppose the Elves finish writing their items’ Calories and end up with the following list:

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

This list represents the Calories of the food carried by five Elves:

  • The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories.
  • The second Elf is carrying one food item with 4000 Calories.
  • The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories.
  • The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories.
  • The fifth Elf is carrying one food item with 10000 Calories.

In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they’d like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf).

Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?

To begin, get your puzzle input.

Part One: Solution

input = Kino.Input.textarea("Please paste your input file:")
input_str = input |> Kino.Input.read()
input_list = input_str |> String.split("\n")
["5229", "1021", "2051", "4766", "2272", "5810", "4688", "2324", "2108", "1555", "1221", "4146",
 "5044", "2238", "4504", "", "4800", "3333", "1171", "5362", "6213", "3200", "1185", "5839", "4075",
 "3956", "6688", "4293", "2244", "", "6719", "2596", "5233", "5371", "4802", "5901", "6093", "2420",
 "2593", "4093", "1909", "3851", "4143", "", "4353", "6425", "2546", "6368", "1939", "8550", ...]
input_list
|> Enum.reduce({0, 0}, fn
  "", {current, max} when current > max ->
    {0, current}

  "", {_, max} ->
    {0, max}

  amt, {current, max} ->
    {current + String.to_integer(amt), max}
end)
|> then(fn {_, max} -> max end)
72017

How many total Calories is that Elf carrying?

Your puzzle answer was 72017.

The first half of this puzzle is complete! It provides one gold star: *

Part Two: Prompt

By the time you calculate the answer to the Elves’ question, they’ve already realized that the Elf carrying the most Calories of food might eventually run out of snacks.

To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.

In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000.

Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?

Part Two: Solution

This solution was admittedly aiming for performance over clarity. See the newly added Alternative Solution section below for a more idiomatic approach.

Day01.find_top_elves/2 iterates over each input line only once, accumulating the total for each individual elf.

When a newline ("") is reached, we add that elf’s total to the current leaderboard list of totals, and drop the lowest value from the leaderboard.

This leaders list initially holds zeroes for the number of leaders we want to keep (e.g. when looking for the top 3 totals, the initial leaders list is [0, 0, 0]).

Bonus performance:

Use Day01.rank/1 instead of Enum.sort(list, :asc) if sorting performance is a concern.

Day01.rank/1 assumes the tail of the list is sorted ascending, so exits the recursion as soon as a larger item is met.

defmodule Day01 do
  def find_top_n(input, top_n \\ 1)

  def find_top_n(input, top_n) when is_binary(input) do
    input |> String.split("\n") |> find_top_n(top_n)
  end

  def find_top_n(input, top_n) when is_list(input) do
    leaders = List.duplicate(0, top_n)

    input
    |> Enum.reduce({0, leaders}, &apply_line/2)
    |> then(&update_leaders/1)
  end

  defp apply_line("", value_and_leaders) do
    {0, update_leaders(value_and_leaders)}
  end

  defp apply_line(line_amt, {acc, top}) do
    {acc + String.to_integer(line_amt), top}
  end

  defp update_leaders({value, leaders}) do
    [value | leaders] |> Enum.sort(:asc) |> Enum.drop(1)
  end

  def rank([a | [b | _]] = list) when a <= b, do: list
  def rank([a | [b | rest]]), do: [b | rank([a | rest])]
  def rank([_] = end_of_list), do: end_of_list
end
{:module, Day01, <<70, 79, 82, 49, 0, 0, 12, ...>>, {:rank, 1}}
Day01.find_top_n(input_list, 1) |> List.first()
72017
Day01.find_top_n(input_list, 3) |> Enum.take(3) |> Enum.sum()
212520

How many Calories are those Elves carrying in total?

Your puzzle answer was 212520.

Both parts of this puzzle are complete! They provide two gold stars: **

At this point, you should return to your Advent calendar and try another puzzle.

If you still want to see it, you can get your puzzle input.

Alternative Solution

In the spirit of clarity over performance, it would be more idiomatic to simply calculate all the totals, then sort the list and take the desired number of “top” entries:

sorted_totals = fn input ->
  input
  |> String.split("\n\n")
  |> Enum.map(fn group ->
    group
    |> String.split("\n")
    |> Enum.map(&String.to_integer/1)
    |> Enum.sum()
  end)
  |> Enum.sort(:desc)
end
#Function<42.3316493/1 in :erl_eval.expr/6>
# Part 1:
input_str |> sorted_totals.() |> List.first()
72017
# Part 2:
input_str |> sorted_totals.() |> Enum.take(3) |> Enum.sum()
212520

ExUnit Exploration

ExUnit.start(auto_run: false)

defmodule Day01Test do
  use ExUnit.Case, async: false

  setup_all do
    [
      input: "1000\n2000\n3000\n\n4000\n\n5000\n6000\n\n7000\n8000\n9000\n\n10000"
    ]
  end

  describe "find_top_n/2" do
    test "returns top 1 total", %{input: input} do
      assert Day01.find_top_n(input, 1) == [24000]
    end

    test "returns top 3 totals, in ascending order", %{input: input} do
      assert Day01.find_top_n(input, 3) == [10000, 11000, 24000]
    end
  end
end

ExUnit.run()
..
Finished in 0.00 seconds (0.00s async, 0.00s sync)
2 tests, 0 failures

Randomized with seed 712519
%{excluded: 0, failures: 0, skipped: 0, total: 2}