Guard Gallivant

Advent of Code 2024 [Day 6]

06-12-2024

The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab… in the year 1518! It turns out that having direct access to history is very convenient for a group of historians.

You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab.

Maybe you can work out where the guard will go ahead of time so that The Historians can search safely?

You start by making a map (your puzzle input) of the situation. For example:

....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...

The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #.

Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps:

Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes):

....#.....
....^....#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...

Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction:

....#.....
........>#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#...

Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward:

....#.....
.........#
..........
..#.......
.......#..
..........
.#......v.
........#.
#.........
......#...

This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent):

....#.....
.........#
..........
..#.......
.......#..
..........
.#........
........#.
#.........
......#v..

By predicting the guard’s route, you can determine which specific positions in the lab will be in the patrol path. Including the guard’s starting position, the positions visited by the guard before leaving the area are marked with an X:

....#.....
....XXXXX#
....X...X.
..#.X...X.
..XXXXX#X.
..X.X.X.X.
.#XXXXXXX.
.XXXXXXX#.
#XXXXXXX..
......#X..

In this example, the guard will visit 41 distinct positions on your map.

Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?

type Position = {
  x: number;
  y: number;
};

type Direction = "^" | ">" | "v" | "<";

class Guard {
  pos: Position;
  dir: Direction;
  grid: string[][];
  visited: Set<string>;

  constructor(grid: string[][]) {
    this.grid = grid;
    this.visited = new Set();
    [this.pos, this.dir] = this.findStart();
    this.markVisited();
  }

  private findStart(): [Position, Direction] {
    for (let y = 0; y < this.grid.length; y++) {
      for (let x = 0; x < this.grid[y].length; x++) {
        if ("^>v<".includes(this.grid[y][x])) {
          return [{ x, y }, this.grid[y][x] as Direction];
        }
      }
    }
    throw new Error("No start position found");
  }

  private markVisited() {
    if (this.pos.y < 0 || this.pos.y >= this.grid.length ||
      this.pos.x < 0 || this.pos.x >= this.grid[0].length) {
      return;
    }
    this.visited.add(`${this.pos.x},${this.pos.y}`);
  }

  private turnRight() {
    const dirs: Direction[] = ["^", ">", "v", "<"];
    this.dir = dirs[(dirs.indexOf(this.dir) + 1) % 4];
  }

  private isBlocked(): boolean {
    const nextPos = this.getNextPosition();
    if (nextPos.y < 0 || nextPos.y >= this.grid.length ||
        nextPos.x < 0 || nextPos.x >= this.grid[0].length) {
      return false;
    }
    return this.grid[nextPos.y][nextPos.x] === "#";
  }

  private getNextPosition(): Position {
    const moves = {
      "^": { dx: 0, dy: -1 },
      ">": { dx: 1, dy: 0 },
      "v": { dx: 0, dy: 1 },
      "<": { dx: -1, dy: 0 },
    };
    const move = moves[this.dir];
    return {
      x: this.pos.x + move.dx,
      y: this.pos.y + move.dy,
    };
  }

  private moveForward() {
    this.pos = this.getNextPosition();
    this.markVisited();
  }

  isOutOfBounds(): boolean {
    return this.pos.y < 0 || 
           this.pos.y >= this.grid.length ||
           this.pos.x < 0 || 
           this.pos.x >= this.grid[0].length;
  }

  step() {
    if (this.isBlocked()) {
      this.turnRight();
    } else {
      this.moveForward();
    }
  }

  getVisitedCount(): number {
    return this.visited.size;
  }
}

async function main() {
  const input = await Deno.readTextFile("input.txt");
  const grid = input.trim().split("\n").map(line => line.split(""));
  
  const guard = new Guard(grid);
  while (!guard.isOutOfBounds()) {
    guard.step();
  }

  console.log(`The guard visited ${guard.getVisitedCount()} distinct positions`);
}

main().catch((err) => console.error(err));

While The Historians begin working around the guard’s patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab’s guard post on the walls of the closet.

Returning after what seems like only a few seconds to The Historians, they explain that the guard’s patrol area is simply too large for them to safely search the lab without getting caught.

Fortunately, they are pretty sure that adding a single new obstruction won’t cause a time paradox. They’d like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search.

To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can’t be placed at the guard’s starting position - the guard is there right now and would notice.

In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right.

Option one, put a printing press next to the guard’s starting position:

....#.....
....+---+#
....|...|.
..#.|...|.
....|..#|.
....|...|.
.#.O^---+.
........#.
#.........
......#...

Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area:

....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
......O.#.
#.........
......#...

Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant:

....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----+O#.
#+----+...
......#...

Option four, put an alchemical retroencabulator near the bottom left corner:

....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
..|...|.#.
#O+---+...
......#...

Option five, put the alchemical retroencabulator a bit to the right instead:

....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
....|.|.#.
#..O+-+...
......#...

Option six, put a tank of sovereign glue right next to the tank of universal solvent:

....#.....
....+---+#
....|...|.
..#.|...|.
..+-+-+#|.
..|.|.|.|.
.#+-^-+-+.
.+----++#.
#+----++..
......#O..

It doesn’t really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose.

You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?

type Position = {
  x: number;
  y: number;
};

type Direction = "^" | ">" | "v" | "<";

class Guard {
  pos: Position;
  dir: Direction;
  grid: string[][];
  visited: Map<string, number>;
  private readonly LOOP_THRESHOLD = 1000;

  constructor(grid: string[][], startPos: Position, startDir: Direction) {
    this.grid = grid.map(row => [...row]);
    this.pos = { ...startPos };
    this.dir = startDir;
    this.visited = new Map();
  }

  private getKey(pos: Position, dir: Direction): string {
    return `${pos.x},${pos.y},${dir}`;
  }

  private turnRight() {
    const dirs: Direction[] = ["^", ">", "v", "<"];
    this.dir = dirs[(dirs.indexOf(this.dir) + 1) % 4];
  }

  private isBlocked(): boolean {
    const nextPos = this.getNextPosition();
    if (nextPos.y < 0 || nextPos.y >= this.grid.length ||
        nextPos.x < 0 || nextPos.x >= this.grid[0].length) {
      return false;
    }
    return this.grid[nextPos.y][nextPos.x] === "#" || 
           this.grid[nextPos.y][nextPos.x] === "O";
  }

  private getNextPosition(): Position {
    const moves = {
      "^": { dx: 0, dy: -1 },
      ">": { dx: 1, dy: 0 },
      "v": { dx: 0, dy: 1 },
      "<": { dx: -1, dy: 0 },
    };
    const move = moves[this.dir];
    return {
      x: this.pos.x + move.dx,
      y: this.pos.y + move.dy,
    };
  }

  step(): boolean {
    const key = this.getKey(this.pos, this.dir);
    const visits = this.visited.get(key) || 0;
    this.visited.set(key, visits + 1);

    if (visits >= this.LOOP_THRESHOLD) {
      return false;
    }

    if (this.isBlocked()) {
      this.turnRight();
    } else {
      this.pos = this.getNextPosition();
    }

    return this.pos.y < 0 || 
           this.pos.y >= this.grid.length ||
           this.pos.x < 0 || 
           this.pos.x >= this.grid[0].length;
  }
}

async function findLoopPositions(input: string): Promise<number> {
  const grid = input.trim().split("\n").map(line => line.split(""));

  let startPos: Position = { x: 0, y: 0 };
  let startDir: Direction = "^";
  
  for (let y = 0; y < grid.length; y++) {
    for (let x = 0; x < grid[y].length; x++) {
      if ("^>v<".includes(grid[y][x])) {
        startPos = { x, y };
        startDir = grid[y][x] as Direction;
        grid[y][x] = ".";
      }
    }
  }

  const validPositions = new Set<string>();

  for (let y = 0; y < grid.length; y++) {
    for (let x = 0; x < grid[0].length; x++) {
      if (grid[y][x] === "." && (x !== startPos.x || y !== startPos.y)) {
        const testGrid = grid.map(row => [...row]);
        testGrid[y][x] = "O";

        const guard = new Guard(testGrid, startPos, startDir);
        let outOfBounds = false;
        let steps = 0;
        const MAX_STEPS = 10000;
        
        while (steps < MAX_STEPS && !outOfBounds) {
          outOfBounds = guard.step();
          steps++;
        }

        if (!outOfBounds) {
          validPositions.add(`${x},${y}`);
        }
      }
    }
  }

  return validPositions.size;
}

async function main() {
  const input = await Deno.readTextFile("input.txt");
  const result = await findLoopPositions(input);
  console.log(`There are ${result} possible positions for the obstruction`);
}

main().catch((err) => console.error(err));
Click to show the input
.....#......................................................#...................#.........................................#..#....
.......................#.......#...............................................#.................#...#.......#..............#.....
.........#.................................................................#.....................##...............................
.....#..#.............#.......................#..#....#............#.............................................#................
............#................##............................................#.##..................#.................#.....#...#....
....................................................................#..#.................#.....#................#....#.....#......
.#.........##.................##................#..............................................#..................................
...................#..................#.......#......#......................#..#...................#.........#...............#.#..
.......................#.#.........#...............#....................#........#.............#..................................
......#...........#........................................#........#.........#...............#.#.........#.......................
...#...........................................................#...........#............................#.........................
...........#............................#.#........#...#........#........................................................#........
.........#................................................#...#..#........#............#................#.........................
..#.....................................................................#...............#.........#....#.......#..................
.......................#....#..#............#.........#.............#...................##....................................#...
..................#...................................................................#.....................#...................#.
............................#..........................#.....#...........##.......................................................
........................#.............................#...............#..............................#.........................#..
.....................#..........#...#.....#....#..............#...........................................#...............#.#.....
...................................#.................................#......#..................#..................................
.#.....#.......##......#..................#...............................................#.........................#.........#...
.................#...............#..............................#............................................#......#.............
...#.........#................#...#....................#......................#.#......#.............#............................
.............#..........##....#...#................#.............#.............#............................................#.....
.....#............................................................................................................#...............
........................#..........................##........#........................................#........#..................
..........................#.....##.#.............#.........#..............................#..............................#........
..............#.....................#...............................................#..................................#..........
...#................................................#.........#.....................#..........................................#..
.##..............#..........#......................................................................#.........#........#.........#.
...##.#.....#........#..........................#.............................#..........#.#..#...................................
..................................#...#......#......#................#..#.....................................#...#...............
.........................................................................................#..................#......#..............
.................#....................#..#....#..............................#........##...#.......#...............#..............
...#.................#................#..................................#..................##....##.....#............#...........
..........#...#....................##......................#.....#...........#......#......#.............##....#...#........#.#...
............................#......#.........#..............................................................#........#............
.........................................#.........................................................#...............#.............#
.....#..........#..#........#................................................................................##......#............
.#................#.....................................................................................#.....#...................
..............#........#..................................#..............................##.......................................
........................#.....................#..............................#..................#.............................#.##
#...........................................................#..##........#........................................................
..............#...............#.........#...........^.....................................................#...#.........##..#.....
......................................................#.......................................#..............#...............#....
...#....#..................#....#.......................#.#..........#.......#.................#................................#.
#.........................................................................................................#.......................
..........................#......................................................................#.............#..................
................#...............................................................#........#........................................
..........#............#...............#.#........................................................................................
....#.....#............#.....##.........#......##.................#.......#................#...............................#...#..
................................................................................#...#.......................................#.....
.#........................................#.................................................................#.#...................
.......#....#...................................................................................#...........#..#.............#....
...#...#...............................................................................................................#..........
..#....................................#......#.................#.........................................................#.......
...........................................#......#.........#.##........##..#.........#..........................#....##.#....#...
.........................#...............#............................................................................#...........
................................................#................#..................#..#...........#.......................#.....#
..........................................................#..........#........................................#...................
..................#...................#................##.........#...........................#...................................
............................#.................................................................#...........#.#.....................
................#.......................#.........................................................................#....#..........
#..........#..............#.#............................................................................................#........
..........................................................................................#.......#.........................#....#
...........................................#.......#................................................................#...#.........
..#...................#........................................#..............#.......................#...........................
.......................#..............................#...........................#......#......................#........#........
.....#................................................................................#....#......................................
..#..................................#.........#....#............#....#..............#.............#......#.........#......#....#.
.......##.................................................................................................#.#....#................
............................................#.....#...................#...........#.........#.....................................
...............#.........................................#.............................#.........................#............#...
..............................................##..................................................#........................#......
..................................................................................................#.................#............#
......................#.......................#.........#......................................................................#..
..#...........................#...........................................................................#.....#........#........
..........#....................#...........................##................................................................#....
.........#........#...........................................#........##.........................................................
....#.............................#....................#.................#..........................#........................#....
.......................................#...#....#...............................................#.................................
............#............................................#..............................#..........#......#.......................
.#..............................#...........#........#...............................#.#......#..................................#
#................#..#.............................................................................................................
................................#................#............#....#.#..................##.....................#...............#.#
#....##................#...........#....#..#..........#.....................#..........................#.....................#....
............................................................................................#.....................................
.......................#................................................##..................................#.....................
....#.....#..#................................................................................................##..................
..........................#......#...#...#..........#...#................#.................................................#......
............................#....#.#.......#..........#............................................#..............................
......#...........#......................#..#.....................................................................................
.........................................#...................................................##...............#............#...##.
...................................#.#............................................................................................
......................#........##..................................................#..............................................
...................#......................................................#......#.............................#...........#......
......#................#................................................................................#..................#......
..#.........................#.....#..............#.........#...................#.......................................#..........
..................#..............................................#......#.#.......................................................
...........#.....................................................................#.......................#........................
.......#.........###.....................#........................................................................................
...............#...#..........#........................#....................#......#............#..................#..............
.............#.......#.............#....................................................#.....................................#...
.............................................................................#.#...............................#..#...............
.........##..........#..#.#.................................................................................#................#....
.#..................#.....................................#...................#.#..............#...........................#......
........#.....#...........................#..........................#.............................#...............#..............
#.........#.#.......................................................................................................#.............
..#...................................................................#............#...#.........#................................
..................#......#........#...........#......................#........#..#.......................................#...#..#.
.......................................................#.............#...........#............................#............#......
..............................................#....................................................................#..............
.............#....................#.......................#.............#..........#.........#.............#....#.......#.....#...
...#...................#...............#........#.............#.................#..........#........#................#............
...........#...............#.....................#.................................................#...#.....#.....#..............
....#......................................#......#..............................#...........#.....#..................#...........
#.........#...................#.........#............#............#..............#..........#...........#...#.#..##...............
...........................................................#..................#......#..................#...............#.........
...........#.......................#.........................................................#.......#..............#..........#..
.................................#.....#.....#..............................#..........#..............#............#..............
...............#.......................................................................##.........#...........................#...
....#...............#.........#.#...........#.......#.#..#....#...................................................................
.........#.............................................#.......................................................#..........##......
......................................#...............#.......#..#..#.#...................#....................#.#................
.................#..................................................................#..........................#.....#......#.#...
..#...........#..................#..............#.....#......#.................#..............##.......#...#.......#.......#......
......................................#.....................#..........#............................................##.#..........
#......#................#........................................................#....#....##..................#.................#
............##..............##..........#........##.....................................#..........#..............................
.#.##............#.................#...................#....#...#...............................................#.................