Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2024 - Day 9

2024/elixir/livebooks/day09.livemd

Advent of Code 2024 - Day 9

Mix.install([
  {:kino_aoc, "~> 0.1"},
  {:flow, "~> 1.2"}
])

Introduction

— Day 9: Disk Fragmenter —

Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls.

While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He’s trying to make more contiguous free space by compacting all of the files, but his program isn’t working; you offer to help.

He shows you the disk map (your puzzle input) he’s already generated. For example:

2333133121414131402

The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space.

So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them).

Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks:

0..111....22222

The first example above, 2333133121414131402, represents these individual blocks:

00…111…2…333.44.5555.6666.777.888899

The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this:

0..111....22222
02.111....2222.
022111....222..
0221112...22...
02211122..2....
022111222......

The first example requires a few more steps:

00...111...2...333.44.5555.6666.777.888899
009..111...2...333.44.5555.6666.777.88889.
0099.111...2...333.44.5555.6666.777.8888..
00998111...2...333.44.5555.6666.777.888...
009981118..2...333.44.5555.6666.777.88....
0099811188.2...333.44.5555.6666.777.8.....
009981118882...333.44.5555.6666.777.......
0099811188827..333.44.5555.6666.77........
00998111888277.333.44.5555.6666.7.........
009981118882777333.44.5555.6666...........
009981118882777333644.5555.666............
00998111888277733364465555.66.............
0099811188827773336446555566..............

The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks’ position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead.

Continuing the first example, the first few blocks’ position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928.

Compact the amphipod’s hard drive using the process he requested. What is the resulting filesystem checksum?

— Part Two —

Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea?

The eager amphipod already has a new plan: rather than move individual blocks, he’d like to try compacting the files on his disk by moving whole files instead.

This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move.

The first example from above now proceeds differently:

00...111...2...333.44.5555.6666.777.888899
0099.111...2...333.44.5555.6666.777.8888..
0099.1117772...333.44.5555.6666.....8888..
0099.111777244.333....5555.6666.....8888..
00992111777.44.333....5555.6666.....8888..

The process of updating the filesystem checksum is the same; now, this example’s checksum would be 2858.

Start over, now compacting the amphipod’s hard drive using this new method instead. What is the resulting filesystem checksum?

Puzzle

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "9", System.fetch_env!("LB_AOC_SESSION"))
IO.puts(puzzle_input)

Parser

Code - Parser

defmodule Parser do
  def parse(input) do
  end
end

Tests - Parser

ExUnit.start(autorun: false)

defmodule ParserTest do
  use ExUnit.Case, async: true
  import Parser

  @input ""
  @expected nil

  test "parse test" do
    assert parse(@input) == @expected
  end
end

ExUnit.run()

Part One

Code - Part 1

defmodule PartOne do
  def solve(input) do
    IO.puts("--- Part One ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    blocks =
      input
      |> String.codepoints()
      |> Stream.map(&String.to_integer(&1))
      |> Stream.chunk_every(2, 2)
      |> Stream.with_index()
      |> Stream.map(fn
        {[file, space], id} ->
          left =
            id
            |> Integer.to_string()
            |> List.duplicate(file)

          right =
            "."
            |> List.duplicate(space)

          left ++ right

        {[file], id} ->
          id
          |> Integer.to_string()
          |> List.duplicate(file)
      end)
      |> Enum.to_list()
      |> List.flatten()

    0..(length(blocks) - 1)
    |> Enum.reduce_while(blocks, fn _, compacted_blocks ->
      case Enum.find_index(compacted_blocks, &(&1 == ".")) do
        nil ->
          {:halt, compacted_blocks}

        _ ->
          {new_compacted_blocks, number} = one_block_compacting(compacted_blocks)

          index =
            new_compacted_blocks
            |> Enum.find_index(&(&1 == "."))

          case index do
            nil ->
              new_compacted_blocks = new_compacted_blocks ++ [number]

              {:cont, new_compacted_blocks}

            _ ->
              new_compacted_blocks =
                new_compacted_blocks
                |> List.replace_at(index, number)

              {:cont, new_compacted_blocks}
          end
      end
    end)
    |> Stream.with_index()
    |> Stream.map(fn {val, index} -> String.to_integer(val) * index end)
    |> Enum.sum()
  end

  # def file_compacting(blocks) do
  #   case Enum.find_index(blocks, &(&1 == ".")) do
  #       nil -> blocks
  #       _ ->

  #   end
  # end

  def one_block_compacting(blocks) do
    rest =
      blocks
      |> Enum.slice(0, length(blocks) - 1)

    case List.last(blocks) do
      "." ->
        one_block_compacting(rest)

      val ->
        {rest, val}
    end
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

defmodule PartOneTest do
  use ExUnit.Case, async: true
  import PartOne

  @input "2333133121414131402"
  @expected 1928

  test "part one" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 1

PartOne.solve(puzzle_input)

Part Two

Code - Part 2

defmodule PartTwo do
  def solve(input) do
    IO.puts("--- Part Two ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    blocks =
      input
      |> String.codepoints()
      |> Stream.map(&String.to_integer(&1))
      |> Stream.with_index()
      |> Stream.map(fn {size, index} ->
        case Integer.mod(index, 2) do
          0 ->
            # files
            id = div(index, 2)
            [Integer.to_string(id), size]

          1 ->
            # free space
            [".", size]
        end
      end)
      |> Enum.to_list()

    fill_blocks(blocks)
    |> Enum.map(fn [type, size] ->
      List.duplicate(type, size)
    end)
    |> List.flatten()
    |> Stream.map(&String.replace(&1, ".", "0"))
    |> Stream.map(&String.to_integer(&1))
    |> Stream.with_index()
    |> Stream.map(fn {val, index} -> val * index end)
    |> Enum.sum()
  end

  def fill_blocks(blocks) do
    blocks
    |> Enum.filter(fn [type, _] -> type != "." end)
    |> Enum.reverse()
    |> Enum.reduce(blocks, fn [_, file_size] = file, acc ->
      index_space = Enum.find_index(acc, fn [type, size] -> type == "." and size >= file_size end)
      index_file = Enum.find_index(acc, &(&1 == file))

      cond do
        index_space == nil or index_space > index_file ->
          acc

        true ->
          [".", space_size] = Enum.at(acc, index_space)

          acc
          |> List.replace_at(index_file, [".", file_size])
          |> List.replace_at(index_space, file)
          |> List.insert_at(index_space + 1, [".", space_size - file_size])
          |> merge_spaces()
      end
    end)
  end

  # merge the free spaces [[".", 3], [".", 2]] = [".", 5]
  def merge_spaces(blocks) do
    blocks
    |> Enum.reduce([], fn [type, size], acc ->
      case List.last(acc) do
        nil ->
          [[type, size]]

        [last_type, last_size] ->
          cond do
            type == "." and last_type == "." ->
              List.replace_at(acc, -1, [".", size + last_size])

            type == "." and size == 0 ->
              acc

            true ->
              List.insert_at(acc, -1, [type, size])
          end
      end
    end)
  end
end

Tests - Part 2

ExUnit.start(autorun: false)

defmodule PartTwoTest do
  use ExUnit.Case, async: true
  import PartTwo

  @input "2333133121414131402"
  @expected 2858

  test "part two" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input)