Day 3: Lobby
Mix.install([
{:kino, "~> 0.18.0"}
])
Description
You descend a short staircase, enter the surprisingly vast lobby, and are quickly cleared by the security checkpoint. When you get to the main elevators, however, you discover that each one has a red light above it: they’re all offline.
“Sorry about that,” an Elf apologizes as she tinkers with a nearby control panel. “Some kind of electrical surge seems to have fried them. I’ll try to get them online soon.”
You explain your need to get further underground. “Well, you could at least take the escalator down to the printing department, not that you’d get much further than that without the elevators working. That is, you could if the escalator weren’t also offline.”
“But, don’t worry! It’s not fried; it just needs power. Maybe you can get it running while I keep working on the elevators.”
input = Kino.Input.textarea("Please paste your input file:")
ranges = input
|> Kino.Input.read()
|> String.splitter("\n", trim: true)
Part 1
There are batteries nearby that can supply emergency power to the escalator for just such an occasion. The batteries are each labeled with their joltage rating, a value from 1 to 9. You make a note of their joltage ratings (your puzzle input). For example:
987654321111111
811111111111119
234234234234278
818181911112111
The batteries are arranged into banks; each line of digits in your input corresponds to a single bank of batteries. Within each bank, you need to turn on exactly two batteries; the joltage that the bank produces is equal to the number formed by the digits on the batteries you’ve turned on. For example, if you have a bank like 12345 and you turn on batteries 2 and 4, the bank would produce 24 jolts. (You cannot rearrange batteries.)
You’ll need to find the largest possible joltage each bank can produce. In the above example:
- In 987654321111111, you can make the largest joltage possible, 98, by turning on the first two batteries.
- In 811111111111119, you can make the largest joltage possible by turning on the batteries labeled 8 and 9, producing 89 jolts.
- In 234234234234278, you can make 78 by turning on the last two batteries (marked 7 and 8).
- In 818181911112111, the largest joltage you can produce is 92.
The total output joltage is the sum of the maximum joltage from each bank, so in this example, the total output joltage is 98 + 89 + 78 + 92 = 357.
defmodule BatteryBank do
@doc """
Greedy algorithm to select k digits that form the maximum number
while maintaining their relative order.
Time complexity: O(n*k) where n is total digits and k is digits to select
"""
def max_joltage(bank, k) do
bank
|> String.graphemes()
|> select_max_digits(k)
|> Enum.join()
|> String.to_integer()
end
defp select_max_digits(digits, k) do
n = length(digits)
skip_budget = n - k
do_select(digits, k, skip_budget, [])
end
# Base case: no more digits needed
defp do_select(_, 0, _, acc), do: Enum.reverse(acc)
# Recursive case: greedily pick the best digit within our window
defp do_select(digits, k, skip_budget, acc) do
window_size = skip_budget + 1
window = Enum.take(digits, window_size)
# Find the maximum digit and its position
{max_digit, max_idx} =
window
|> Enum.with_index()
|> Enum.max_by(fn {digit, _idx} -> digit end)
# Continue with remaining digits after the selected one
remaining = Enum.drop(digits, max_idx + 1)
new_skip_budget = skip_budget - max_idx
do_select(remaining, k - 1, new_skip_budget, [max_digit | acc])
end
end
Part Two
The escalator doesn’t move. The Elf explains that it probably needs more joltage to overcome the static friction of the system and hits the big red “joltage limit safety override” button. You lose count of the number of times she needs to confirm “yes, I’m sure” and decorate the lobby a bit while you wait.
Now, you need to make the largest joltage by turning on exactly twelve batteries within each bank.
The joltage output for the bank is still the number formed by the digits of the batteries you’ve turned on; the only difference is that now there will be 12 digits in each bank’s joltage output instead of two.
Consider again the example from before:
987654321111111
811111111111119
234234234234278
818181911112111
Now, the joltages are much larger:
- In 987654321111111, the largest joltage can be found by turning on everything except some 1s at the end to produce 987654321111.
- In the digit sequence 811111111111119, the largest joltage can be found by turning on everything except some 1s, producing 811111111119.
- In 234234234234278, the largest joltage can be found by turning on everything except a 2 battery, a 3 battery, and another 2 battery near the start to produce 434234234278.
- In 818181911112111, the joltage 888911112111 is produced by turning on everything except some 1s near the front.
The total output joltage is now much larger: 987654321111 + 811111111119 + 434234234278 + 888911112111 = 3121910778619.
Results
defmodule Benchmark do
def run(fun, runs \\ 100) do
fun.()
times =
for _ <- 1..runs do
{time, _result} = :timer.tc(fun)
time
end
avg_time = Enum.sum(times) / runs
min_time = Enum.min(times)
max_time = Enum.max(times)
{avg_time / 1000, min_time / 1000, max_time / 1000}
end
def format_time(ms) when ms < 0.001, do: "#{Float.round(ms * 1000, 3)} μs"
def format_time(ms) when ms < 1, do: "#{Float.round(ms, 3)} ms"
def format_time(ms) when ms < 1000, do: "#{Float.round(ms, 2)} ms"
def format_time(ms), do: "#{Float.round(ms / 1000, 2)} s"
end
IO.puts("\n╔══════════════════════════════════════════════════════════╗")
IO.puts("║ DAY 03 ║")
IO.puts("╚══════════════════════════════════════════════════════════╝\n")
{time, result} =
:timer.tc(fn ->
ranges
|> Enum.map(&BatteryBank.max_joltage(&1, 2))
|> Enum.sum()
end)
{avg, min, max} =
Benchmark.run(fn ->
ranges
|> Enum.map(&BatteryBank.max_joltage(&1, 2))
|> Enum.sum()
end)
IO.puts("Part 1: #{result}")
IO.puts(" Time: #{Benchmark.format_time(time / 1000)}")
IO.puts(" Avg: #{Benchmark.format_time(avg)} (min: #{Benchmark.format_time(min)}, max: #{Benchmark.format_time(max)})")
{time, result} =
:timer.tc(fn ->
ranges
|> Enum.map(&BatteryBank.max_joltage(&1, 12))
|> Enum.sum()
end)
{avg, min, max} =
Benchmark.run(fn ->
ranges
|> Enum.map(&BatteryBank.max_joltage(&1, 12))
|> Enum.sum()
end)
IO.puts("\nPart 2: #{result}")
IO.puts(" Time: #{Benchmark.format_time(time / 1000)}")
IO.puts(" Avg: #{Benchmark.format_time(avg)} (min: #{Benchmark.format_time(min)}, max: #{Benchmark.format_time(max)})")