question: --- Day 6: Guard Gallivant ---
  
  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:
  
  If there is something directly in front of you, turn right 90 degrees.
  Otherwise, take a step forward.
  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?
  
  Your puzzle answer was 4890.
  
  --- Part Two ---
  
  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?
solution: from enum import IntEnum, auto
  from dataclasses import dataclass, field
  
  in_date = ""
  
  with open("input.txt") as f:
      in_date = f.read()
  
  
  class Direction(IntEnum):
      Up = auto()
      Right = auto()
      Down = auto()
      Left = auto()
  
  
  @dataclass
  class Position:
      x: int
      y: int
  
  
  @dataclass
  class Guardian:
      Pos: Position
      Dir: Direction
      Walks: set = field(default_factory=lambda: set())
      CurrentWalk: list = field(default_factory=lambda: list())
      RepeatedWalks: int = 0
      LastSteps: list = field(default_factory=lambda: list())
  
      def turn_right(self):
          if self.Dir == Direction.Up:
              self.Dir = Direction.Right
          elif self.Dir == Direction.Right:
              self.Dir = Direction.Down
          elif self.Dir == Direction.Down:
              self.Dir = Direction.Left
          elif self.Dir == Direction.Left:
              self.Dir = Direction.Up
          walk = tuple(self.CurrentWalk)
          self.CurrentWalk = []
          if walk in self.Walks:
              self.RepeatedWalks += 1
          if walk:
              # to not add empty walks
              self.Walks.add(walk)
  
      def take_step(self):
          if self.Dir == Direction.Up:
              self.Pos.x -= 1
          elif self.Dir == Direction.Right:
              self.Pos.y += 1
          elif self.Dir == Direction.Down:
              self.Pos.x += 1
          elif self.Dir == Direction.Left:
              self.Pos.y -= 1
          self.CurrentWalk.append((self.Pos.x, self.Pos.y))
          return self.Pos
  
      def next_pos(self):
          posable_pos = Position(self.Pos.x, self.Pos.y)
          if self.Dir == Direction.Up:
              posable_pos.x -= 1
          elif self.Dir == Direction.Right:
              posable_pos.y += 1
          elif self.Dir == Direction.Down:
              posable_pos.x += 1
          elif self.Dir == Direction.Left:
              posable_pos.y -= 1
          return posable_pos
  
      def add_step(self, step: str):
          if len(self.LastSteps) > 99:
              self.LastSteps = self.LastSteps[1:]
          self.LastSteps.append(step)
  
  
  class Action(IntEnum):
      Turn = auto()
      Step = auto()
      Out = auto()
  
  
  class Map:
      def __init__(self, matrix: str):
          self.map = matrix
          self.guardian = self.find_guardian()
  
      def find_guardian(self):
          for i, row in enumerate(self.map):
              for j, col in enumerate(row):
                  if col == "^":
                      self.map[i][j] = "X"
                      return Guardian(Position(i, j), Direction.Up)
  
      def is_open(self, pos: Position):
          if not self.on_map(pos):
              return False, Action.Out
          if self.map[pos.x][pos.y] in {".", "X"}:
              return True, Action.Step
          else:
              return False, Action.Turn
  
      def on_map(self, pos: Position):
          return 0 <= pos.x < len(self.map) and 0 <= pos.y < len(self.map[0])
  
      def mark_visited(self, pos: Position):
          self.map[pos.x][pos.y] = "X"
  
      def count_visited(self):
          return sum([1 for row in self.map for col in row if col == "X"])
  
      def get_spot(self, pos: Position):
          return self.map[pos.x][pos.y]
  
      def __str__(self):
          return "\n".join(["".join(row) for row in self.map])
  
  
  def check_loop(m: Map, iter: int, total: int):
      go_on = True
      last_action = []
      loop_detected = False
      reason = ""
      while go_on:
          curr_pos = m.guardian.Pos
          next_pos = m.guardian.next_pos()
          is_open, action = m.is_open(next_pos)
          if is_open:
              m.guardian.take_step()
              m.mark_visited(curr_pos)
          elif action == Action.Turn:
              m.guardian.turn_right()
          elif action == Action.Out:
              go_on = False
          if last_action.count(action) > 2:
              last_action = last_action[1:]
          last_action.append(action)
          # does guardian stuck in an infinite loop?
          if m.guardian.RepeatedWalks >= 2:
              go_on = False
              loop_detected = True
              reason = "2 repeated walks"
          if last_action == [Action.Turn, Action.Turn, Action.Turn]:
              go_on = False
              loop_detected = True
              reason = "3 turns in a row"
      print(f"Iteration {iter}/{total}")
      return loop_detected
  
  
  raw_map = in_date.strip().split("\n")
  matrixed = [list(row.strip()) for row in raw_map]
  
  possible_obstacles = []
  
  for i in range(len(matrixed)):
      for j in range(len(matrixed[i])):
          if matrixed[i][j] == ".":
              possible_obstacles.append((i, j))
  
  cont = 0
  for i, obs in enumerate(possible_obstacles):
      matrixed = [list(row.strip()) for row in raw_map]
      matrixed[obs[0]][obs[1]] = "#"
      m = Map(matrixed)
      if m.guardian is None:
          continue
      if check_loop(m, i + 1, len(possible_obstacles)):
          cont += 1
  
  print(cont)
  