Powered by AppSignal & Oban Pro

Day 6: Trash Compactor

advent_of_code/2025/day-06.livemd

Day 6: Trash Compactor

Day 6: Trash Compactor

Day 6: Trash Compactor

Part 1

defmodule AdventOfCode2025Day6Part1 do
  def run(input) do
    input
    |> parse_input()
    |> solve()
  end

  defp solve({operations, list_of_lists}) do
    0..(Enum.count(operations) - 1)
    |> Enum.reduce(0, fn i, acc ->
      numbers = 0..(Enum.count(list_of_lists) - 1)
      |> Enum.map(fn j ->
        list_of_lists |> Enum.at(j) |> Enum.at(i)
      end)

      if Enum.at(operations, i) == "+" do
        Enum.sum(numbers) + acc
      else
        Enum.product(numbers) + acc
      end
    end)
  end

  defp parse_input(input) do
    [operations | numbers] = input
    |> String.split("\n", trim: true)
    |> Enum.reverse()

    operations = String.split(operations, " ", trim: true)

    list_of_lists = Enum.reduce(numbers, [], fn line, acc ->
      list = line
      |> String.split(" ", trim: true)
      |> Enum.map(&String.to_integer/1)

      [list | acc]
    end)

    {operations, list_of_lists}
  end
end
input = """
123 328  51 64 
 45 64  387 23 
  6 98  215 314
*   +   *   +  
"""

AdventOfCode2025Day6Part1.run(input)

Part 2

defmodule AdventOfCode2025Day6Part2 do
  def run(input) do
    input
    |> parse_input()
    |> solve()
  end

  defp solve({operations, list_of_lists}) do
    Enum.zip(operations, list_of_lists)
    |> Enum.reduce(0, fn 
      {"*", list}, acc -> acc + Enum.product(list)
      {"+", list}, acc -> acc + Enum.sum(list)
    end)
  end

  defp parse_input(input) do
    [operations | numbers] = input
    |> String.split("\n", trim: true)
    |> Enum.reverse()

    operations = String.split(operations, " ", trim: true)

    chunk_fun = fn charlist, acc ->
      if Enum.all?(charlist, & &1 == ?\s) do
        {:cont, acc, []}
      else
        num = charlist |> Enum.reject(& &1 == ?\s) |> List.to_integer()
        {:cont, [num | acc]}
      end
    end

    after_fun = fn
      acc -> {:cont, acc, []}
    end

    list_of_lists = 
      numbers 
      |> Enum.reverse() 
      |> Enum.map(&String.to_charlist/1)
      |> Enum.zip_with(& &1)
      |> Enum.chunk_while([], chunk_fun, after_fun)

    {operations, list_of_lists}
  end
end
input = """
123 328  51 64 
 45 64  387 23 
  6 98  215 314
*   +   *   +  
"""

AdventOfCode2025Day6Part2.run(input)