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

--- Day 22: Monkey Map ---

Day22/day22.livemd

— Day 22: Monkey Map —

Mix.install([])
:ok

Part 1

The monkeys take you on a surprisingly easy trail through the jungle. They’re even going in roughly the right direction according to your handheld device’s Grove Positioning System.

As you walk, the monkeys explain that the grove is protected by a force field. To pass through the force field, you have to enter a password; doing so involves tracing a specific path on a strangely-shaped board.

At least, you’re pretty sure that’s what you have to do; the elephants aren’t exactly fluent in monkey.

The monkeys give you notes that they took when they last saw the password entered (your puzzle input).

For example:

example_input = """
        ...#
        .#..
        #...
        ....
...#.......#
........#...
..#....#....
..........#.
        ...#....
        .....#..
        .#......
        ......#.

10R5L5R10L4R5L5
"""
"        ...#\n        .#..\n        #...\n        ....\n...#.......#\n........#...\n..#....#....\n..........#.\n        ...#....\n        .....#..\n        .#......\n        ......#.\n\n10R5L5R10L4R5L5\n"

The first half of the monkeys’ notes is a map of the board. It is comprised of a set of open tiles (on which you can move, drawn .) and solid walls (tiles which you cannot enter, drawn #).

The second half is a description of the path you must follow. It consists of alternating numbers and letters:

  • A number indicates the number of tiles to move in the direction you are facing. If you run into a wall, you stop moving forward and continue with the next instruction.
  • A letter indicates whether to turn 90 degrees clockwise (R) or counterclockwise (L). Turning happens in-place; it does not change your current tile.

So, a path like 10R5 means “go forward 10 tiles, then turn clockwise 90 degrees, then go forward 5 tiles”.

You begin the path in the leftmost open tile of the top row of tiles. Initially, you are facing to the right (from the perspective of how the map is drawn).

If a movement instruction would take you off of the map, you wrap around to the other side of the board. In other words, if your next tile is off of the board, you should instead look in the direction opposite of your current facing as far as you can until you find the opposite edge of the board, then reappear there.

For example, if you are at A and facing to the right, the tile in front of you is marked B; if you are at C and facing down, the tile in front of you is marked D:

        ...#
        .#..
        #...
        ....
...#.D.....#
........#...
B.#....#...A
.....C....#.
        ...#....
        .....#..
        .#......
        ......#.

It is possible for the next tile (after wrapping around) to be a wall; this still counts as there being a wall in front of you, and so movement stops before you actually wrap to the other side of the board.

By drawing the last facing you had with an arrow on each tile you visit, the full path taken by the above example looks like this:

        >>v#    
        .#v.    
        #.v.    
        ..v.    
...#...v..v#    
>>>v...>#.>>    
..#v...#....    
...>>>>v..#.    
        ...#....
        .....#..
        .#......
        ......#.

To finish providing the password to this strange input device, you need to determine numbers for your final row, column, and facing as your final position appears from the perspective of the original map. Rows start from 1 at the top and count downward; columns start from 1 at the left and count rightward. (In the above example, row 1, column 1 refers to the empty space with no tile on it in the top-left corner.) Facing is 0 for right (>), 1 for down (v), 2 for left (<), and 3 for up (^). The final password is the sum of 1000 times the row, 4 times the column, and the facing.

In the above example, the final row is 6, the final column is 8, and the final facing is 0. So, the final password is 1000 6 + 4 8 + 0: 6032.

Follow the path given in the monkeys’ notes. What is the final password?

Part 2

As you reach the force field, you think you hear some Elves in the distance. Perhaps they’ve already arrived?

You approach the strange input device, but it isn’t quite what the monkeys drew in their notes. Instead, you are met with a large cube; each of its six faces is a square of 50x50 tiles.

To be fair, the monkeys’ map does have six 50x50 regions on it. If you were to carefully fold the map, you should be able to shape it into a cube!

In the example above, the six (smaller, 4x4) faces of the cube are:

        1111
        1111
        1111
        1111
222233334444
222233334444
222233334444
222233334444
        55556666
        55556666
        55556666
        55556666

You still start in the same position and with the same facing as before, but the wrapping rules are different. Now, if you would walk off the board, you instead proceed around the cube. From the perspective of the map, this can look a little strange. In the above example, if you are at A and move to the right, you would arrive at B facing down; if you are at C and move down, you would arrive at D facing up:

        ...#
        .#..
        #...
        ....
...#.......#
........#..A
..#....#....
.D........#.
        ...#..B.
        .....#..
        .#......
        ..C...#.

Walls still block your path, even if they are on a different face of the cube. If you are at E facing up, your movement is blocked by the wall marked by the arrow:

        ...#
        .#..
     -->#...
        ....
...#..E....#
........#...
..#....#....
..........#.
        ...#....
        .....#..
        .#......
        ......#.

Using the same method of drawing the last facing you had with an arrow on each tile you visit, the full path taken by the above example now looks like this:

        >>v#    
        .#v.    
        #.v.    
        ..v.    
...#..^...v#    
.>>>>>^.#.>>    
.^#....#....    
.^........#.    
        ...#..v.
        .....#v.
        .#v<<<<.
        ..v...#.

The final password is still calculated from your final position and facing from the perspective of the map. In this example, the final row is 5, the final column is 7, and the final facing is 3, so the final password is 1000 5 + 4 7 + 3 = 5031.

Fold the map into a cube, then follow the path given in the monkeys’ notes. What is the final password?

Code

defmodule Day22 do
  @rotation %{
    "R" => %{"R" => "D", "L" => "U", "U" => "R", "D" => "L"},
    "L" => %{"R" => "U", "L" => "D", "U" => "L", "D" => "R"}
  }
  @value %{"R" => 0, "D" => 1, "L" => 2, "U" => 3}
  defp parse_input(input) do
    [m, p] = String.split(input, "\n\n", trim: true)

    map =
      for {l, i} <- String.split(m, "\n", trim: true) |> Enum.with_index(), reduce: %{} do
        acc ->
          r = Map.put(acc, i, %{})

          for {c, j} <- String.graphemes(l) |> Enum.with_index(), reduce: r do
            acc ->
              Map.update!(acc, i, fn x -> Map.put(x, j, c) end)
          end
      end

    {map, String.trim(p)}
  end

  defp find_start(map) do
    for j <- Map.keys(map[0]) |> Enum.sort(), reduce: -1 do
      acc ->
        cond do
          acc < 0 and map[0][j] == "." -> j
          true -> acc
        end
    end
  end

  defp size(map) do
    max_x = Enum.count(map)

    max_y =
      for x <- 0..(max_x - 1), reduce: 0 do
        acc ->
          row_max = Map.keys(map[x]) |> Enum.max()

          cond do
            acc >= row_max -> acc
            true -> row_max
          end
      end

    {max_x, max_y}
  end

  defp follow_path(map, c0, pw) do
    size = size(map)

    for inst <- String.split(pw, ~r/[RL]/, include_captures: true), reduce: {{0, c0}, "R"} do
      acc ->
        {pos, facing} = acc

        {action, q} =
          case Integer.parse(inst) do
            {_, ""} -> {:move, String.to_integer(inst)}
            _ -> {:rotate, @rotation[inst][facing]}
          end

        if action == :rotate do
          {pos, q}
        else
          {new_pos(map, pos, pos, facing, q, size), facing}
        end
    end
  end

  defp new_pos(_map, pos, _last_good_pos, _facing, 0, _size) do
    # IO.inspect(pos, label: "final_pos")
    pos
  end

  defp new_pos(map, {pos_x, pos_y}, last_good_pos, facing, q, size) do
    {size_x, size_y} = size

    {x, y} =
      case facing do
        "R" -> {pos_x, rem(pos_y + 1, size_y + 1)}
        "L" -> {pos_x, if(pos_y == 0, do: size_y, else: pos_y - 1)}
        "D" -> {rem(pos_x + 1, size_x + 1), pos_y}
        "U" -> {if(pos_x == 0, do: size_x, else: pos_x - 1), pos_y}
        _ -> :error
      end

    cond do
      map[x][y] == "#" -> last_good_pos
      map[x][y] == "." -> new_pos(map, {x, y}, {x, y}, facing, q - 1, size)
      map[x][y] == " " -> new_pos(map, {x, y}, last_good_pos, facing, q, size)
      map[x][y] == nil -> new_pos(map, {x, y}, last_good_pos, facing, q, size)
      true -> :error
    end
  end

  def part1(input) do
    {map, pw} =
      input
      |> parse_input()

    c0 = find_start(map)
    {{x, y}, dir} = follow_path(map, c0, pw)
    (x + 1) * 1000 + (y + 1) * 4 + @value[dir]
  end

  def part2(input, n \\ 4) do
    {map, pw} =
      input
      |> parse_input()

    # part2 is quite annoying, not really interesting, just a bunch of if cases
  end
end
warning: variable "cube_size" is unused (if the variable is not meant to be used, prefix it with an underscore)
  Day22/day22.livemd#cell:2mosqc6rf5biexmle6v442eovo4cyoy2:86: Day22.fold_cube/1

warning: variable "pw" is unused (if the variable is not meant to be used, prefix it with an underscore)
  Day22/day22.livemd#cell:2mosqc6rf5biexmle6v442eovo4cyoy2:98: Day22.part2/1
{:module, Day22, <<70, 79, 82, 49, 0, 0, 28, ...>>, {:part2, 1}}

Checking that the example input produces the right result:

Day22.part1(example_input) == 6032
true
input = File.read!("Day22/input.txt")
Day22.part1(input)
93226
Day22.part2(example_input, 4)
{12, 15}
5
Day22.part2(input, 50)
{200, 149}
49