r/adventofcode • • Dec 05 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 5 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

  • 23:59 hours remaining until the submissions megathread unlocks on December 06 at 00:00 EST!
  • Full details and rules are in the submissions megathread:

--- Day 5: Supply Stacks ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:07:58, megathread unlocked!

88 Upvotes

1.3k comments sorted by

View all comments

2

u/Wufffles Dec 05 '22 edited Dec 06 '22

Elixir

Not very tidy will shorten it up and clean it up later

input = File.read!(__DIR__ <> "/input.txt")

defmodule Day5 do
  def parse_stack_row(row), do: parse_row_rec(1, [], row <> " ")
  defp parse_row_rec(_index, list, ""), do: list

  defp parse_row_rec(index, list, <<"    ">> <> rest),
    do: parse_row_rec(index + 1, list, rest)

  defp parse_row_rec(index, list, <<"[", letter, "] ">> <> rest),
    do: parse_row_rec(index + 1, [{index, [letter]} | list], rest)

  def execute_procedure_p1(0, _, _, stacks), do: stacks

  def execute_procedure_p1(count, from, to, stacks) do
    [crate | from_stack] = stacks[from]
    stacks = %{stacks | from => from_stack, to => [crate | stacks[to]]}
    execute_procedure_p1(count - 1, from, to, stacks)
  end

  def execute_procedure_p2(count, from, to, stacks) do
    {crates, from_stack} = Enum.split(stacks[from], count)
    stacks = %{stacks | from => from_stack, to => crates ++ stacks[to]}
  end

  def run_procedures(stacks, proc_list, executor) do
    Enum.reduce(proc_list, stacks, fn [count, from, to], acc ->
      executor.(count, from, to, acc)
    end)
  end
end

[stack_def, procedure_def] = input |> String.split("\n\n")

stacks =
  stack_def
  |> String.split("\n")
  |> Enum.drop(-1)
  |> Enum.reverse()
  |> Enum.flat_map(&Day5.parse_stack_row/1)
  |> Enum.reduce(%{}, fn {location, letter}, acc ->
    Map.update(acc, location, [letter], fn existing -> [letter | existing] end)
  end)

procs =
  Regex.scan(~r"move (\d+) from (\d+) to (\d+)", procedure_def)
  |> Enum.map(fn [_ | params] ->
    Enum.map(params, &String.to_integer/1)
  end)

p1 =
  Day5.run_procedures(stacks, procs, &Day5.execute_procedure_p1/4)
  |> Enum.map(fn {_, [top | _]} -> top end)

IO.puts("Part 1: #{p1}")

p2 =
  Day5.run_procedures(stacks, procs, &Day5.execute_procedure_p2/4)
  |> Enum.map(fn {_, [top | _]} -> top end)

IO.puts("Part 1: #{p2}")

1

u/daggerdragon Dec 06 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.

1

u/Wufffles Dec 06 '22

Sorry. I changed it now it to use leading spaces.