# Load the input, provided as a text file
input =
Path.join(__DIR__, "/05.input.txt")
|> File.read!()
(Source)
The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.
The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.
The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.
They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P.
Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates:
[Z]
[N]
[C] [D]
[M] [P]
1 2 3
Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M:
[Z]
[N]
[M] [D]
[C] [P]
1 2 3
Finally, one crate is moved from stack 1 to stack 2:
[Z]
[N]
[D]
[C] [M] [P]
1 2 3
The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ.
After the rearrangement procedure completes, what crate ends up on top of each stack?
[stacks_input, procedure_input] = String.split(input, ~r/\n\n/, trim: true)
To help manage the state for each stack, I discovered that I could define and spawn a simple process for each one, which defines a simple interface (list, get, push, pop).
defmodule Stack do
def loop(state) do
receive do
{_from, :push, value} ->
loop([value | state])
{from, :pop} ->
[head | tail] = state
send(from, {:reply, head})
loop(tail)
{from, :list} ->
send(from, {:reply, state})
loop(state)
{from, :get, idx} ->
value = Enum.at(state, idx)
send(from, {:reply, value})
loop(state)
end
end
def start_link(state) do
spawn_link(__MODULE__, :loop, [init(state)])
end
def init(state), do: state
def list(pid) do
send(pid, {self(), :list})
receive do
{:reply, value} -> value
end
end
def get(pid, idx) do
send(pid, {self(), :get, idx})
receive do
{:reply, value} -> value
end
end
def push(pid, value) do
send(pid, {self(), :push, value})
:ok
end
def pop(pid) do
send(pid, {self(), :pop})
receive do
{:reply, value} -> value
end
end
end
We define a utility module to initialize and parse various bits of data from the input, as well as instantiate our Stack processes.
defmodule SupplyStacks do
@stacks stacks_input
|> String.split(~r/\n/, trim: true)
@procedure procedure_input
|> String.split(~r/\n/, trim: true)
def init_stacks do
[header | stacks_rev] = @stacks |> Enum.reverse()
stacks =
stacks_rev
|> Enum.reverse()
|> Enum.map(&String.codepoints/1)
parse_header(header)
|> Enum.reduce(%{}, fn {key, idx}, acc ->
Map.put(acc, String.to_integer(key), build_stack(stacks, idx))
end)
end
def init_procedure do
@procedure
|> Enum.map(&parse_procedure_step/1)
end
def parse_procedure_step(str) do
[_ | move_from_to] = Regex.run(~r/move (\d+) from (\d+) to (\d+)/, str)
move_from_to |> Enum.map(&String.to_integer/1)
end
def parse_header(header) do
header
|> String.codepoints()
|> Enum.with_index()
|> Enum.filter(fn {x, _} -> x != " " end)
end
def build_stack(stacks, idx) do
stacks
|> Enum.map(&Enum.at(&1, idx))
|> Enum.filter(fn x -> x != " " end)
|> Stack.start_link()
end
end
A map of our Stack processes. Hooray!
stacks = SupplyStacks.init_stacks()
# %{
# 1 => #PID<0.155.0>,
# 2 => #PID<0.156.0>,
# 3 => #PID<0.157.0>,
# 4 => #PID<0.158.0>,
# 5 => #PID<0.159.0>,
# 6 => #PID<0.160.0>,
# 7 => #PID<0.161.0>,
# 8 => #PID<0.162.0>,
# 9 => #PID<0.163.0>
# }
We can list the contents of each stack to verify that it still matches the input.
Map.keys(stacks)
|> Enum.map(fn x ->
Map.get(stacks, x)
|> Stack.list()
end)
# [
# ["V", "R", "H", "B", "G", "D", "W"],
# ["F", "R", "C", "G", "N", "J"],
# ["J", "N", "D", "H", "F", "S", "L"],
# ["V", "S", "D", "J"],
# ["V", "N", "W", "Q", "R", "D", "H", "S"],
# ["M", "C", "H", "G", "P"],
# ["C", "H", "Z", "L", "G", "B", "J", "F"],
# ["R", "J", "S"],
# ["M", "V", "N", "B", "R", "S", "G", "L"]
# ]
Next, we parse the procedure strings into [move, from, to]
format.
procedure = SupplyStacks.init_procedure()
# [
# [2, 2, 7],
# [8, 5, 6],
# [2, 4, 5],
# [...],
# ...
# ]
Now, we execute each step in the procedure, popping from and pushing to each stack for the appropriate number of crates.
Enum.each(procedure, fn [move, from, to] ->
origin_pid = Map.get(stacks, from)
dest_pid = Map.get(stacks, to)
1..move
|> Enum.each(fn _ ->
crate = Stack.pop(origin_pid)
Stack.push(dest_pid, crate)
end)
end)
# :ok
After executing the procedure, we get the first crate of each stack.
1..9
|> Enum.map(fn x ->
Map.get(stacks, x)
|> Stack.list()
|> List.first()
end)
|> Enum.join()
# "JRVNHHCSJ"
As you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction.
Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001.
The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.
Again considering the example above, the crates begin in the same configuration:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
Moving a single crate from stack 2 to stack 1 behaves the same as before:
[D]
[N] [C]
[Z] [M] [P]
1 2 3
However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration:
[D]
[N]
[C] [Z]
[M] [P]
1 2 3
Next, as both crates are moved from stack 2 to stack 1, they retain their order as well:
[D]
[N]
[C] [Z]
[M] [P]
1 2 3
Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved:
[D]
[N]
[Z]
[M] [C] [P]
1 2 3
In this example, the CrateMover 9001 has put the crates in a totally different order: MCD.
Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack?
stacks2 = SupplyStacks.init_stacks()
# %{
# 1 => #PID<0.1123.0>,
# 2 => #PID<0.1124.0>,
# 3 => #PID<0.1125.0>,
# 4 => #PID<0.1126.0>,
# 5 => #PID<0.1127.0>,
# 6 => #PID<0.1128.0>,
# 7 => #PID<0.1129.0>,
# 8 => #PID<0.1130.0>,
# 9 => #PID<0.1131.0>
# }
The difference here is that we collect the crates and reverse them, prior to pushing them to their new stack one at a time (I didn't feel like adding another interface on the Stack module).
Enum.each(procedure, fn [move, from, to] ->
origin_pid = Map.get(stacks2, from)
dest_pid = Map.get(stacks2, to)
1..move
|> Enum.map(fn _ -> Stack.pop(origin_pid) end)
|> Enum.reverse()
|> Enum.each(fn crate -> Stack.push(dest_pid, crate) end)
end)
# :ok
1..9
|> Enum.map(fn x ->
Map.get(stacks2, x)
|> Stack.list()
|> List.first()
end)
|> Enum.join()
# "GNFBSBJLH"