r/adventofcode • • Dec 07 '22

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


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

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


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:14:47, megathread unlocked!

89 Upvotes

1.3k comments sorted by

View all comments

1

u/seacucumber_kid Dec 07 '22

Elixir

not very satisfied with this

defmodule Day7 do
  def part1(input_file) do
    input_file
    |> parse_input()
    |> Enum.reduce(0, fn {_, size}, acc -> if size <= 100_000, do: acc + size, else: acc end)
  end

  def part2(input_file) do
    fs =
      input_file
      |> parse_input()

    fs
    |> Map.values()
    |> Enum.filter(&(70_000_000 - fs["root"] + &1 >= 30_000_000))
    |> Enum.min()
  end

  defp parse_input(input) do
    input
    |> File.read!()
    |> String.split("$ cd ", trim: true)
    |> Enum.map(fn el ->
      el
      |> String.split("\n", trim: true)
      |> Enum.reject(&String.contains?(&1, ["dir", "$ ls"]))
      |> then(fn [cd | files] ->
        [
          cd
          | Enum.map(files, &(&1 |> String.split(" ") |> hd() |> String.to_integer()))
        ]
      end)
    end)
    |> Enum.reduce({["root"], %{}}, fn [cd | files], {dir, tree} ->
      size = files |> List.wrap() |> Enum.sum()

      case cd do
        "/" ->
          {["root"], Map.merge(tree, %{"root" => size})}

        ".." ->
          {Enum.drop(dir, 1), tree}

        d ->
          {[d | dir],
          tree
          |> Map.merge(%{
            Enum.join([d | dir]) => size
          })
          |> update_rec(dir, size)}
      end
    end)
    |> elem(1)
  end

  defp update_rec(tree, [], _), do: tree

  defp update_rec(tree, [_] = dir, size),
    do: Map.update!(tree, Enum.join(dir), &(&1 + size))

  defp update_rec(tree, [_ | tail] = dir, size) do
    tree = Map.update!(tree, Enum.join(dir), &(&1 + size))
    update_rec(tree, tail, size)
  end
end

Day7.part1("input.txt")
|> IO.inspect(label: "Part 1")

Day7.part2("input.txt")
|> IO.inspect(label: "Part 2")

1

u/daggerdragon Dec 08 '22

Your code block is too long. Please read our article on oversized code, then edit your post to replace the code block with an external link to your code.