2024(6): add verbose bool and write idea for part two out

This commit is contained in:
2024-12-24 17:51:44 +01:00
parent 2144ecc5fb
commit 923f63b2ce
2 changed files with 46 additions and 14 deletions

View File

@ -2,12 +2,7 @@ import numpy as np
from enum import Enum
'''
idee:
sla ook het kleine voorbeeld op
guard_directions = ["^", ">", "v", "<"]
guard_path = [] # list of tuples (x, y)
'''
verbose = False
class Map:
directions = ["^", ">", "v", "<"]
@ -30,20 +25,25 @@ class Map:
"""
next_pos = tuple([self.pos[i] + self.step_per_direction[self.directions.index(self.direction)][i] for i in range(len(self.pos))])
print("next_pos", next_pos)
if verbose:
print("next_pos", next_pos)
return next_pos
def pos_in_map(self, pos):
"""
Returns whether pos is in the map.
"""
print("pos_in_map", pos)
if verbose:
print("pos_in_map", pos)
return pos[0] >= 0 and pos[0] < self.map.shape[0] \
and pos[1] >= 0 and pos[0] < self.map.shape[1]
def look_ahead(self):
next_step = self.next_pos()
print("look_ahead.next_step", next_step)
if verbose:
print("look_ahead.next_step", next_step)
if not self.pos_in_map(next_step):
return self.Tiles.BORDER
if self.map[*next_step] == "#":
@ -89,10 +89,11 @@ class Map:
# Find the location of the guard in the map.
guards = self.seek_guard_in_map()
print(guards)
if verbose:
print(guards)
assert len(guards) == 1, "There should only be one guard in the map."
print(guards)
self.pos = guards[0]
self.trace.append(self.pos)
self.direction = m.map[self.pos]
@ -106,9 +107,11 @@ class Map:
"""
next_tile = self.look_ahead()
print("step.next_tile", next_tile)
if verbose:
print("step.next_tile", next_tile)
if next_tile == self.Tiles.FREE:
# TODO: Really take a step! Do not only turn.
self.pos = self.next_pos()
self.trace.append(self.pos)
return True
@ -137,7 +140,8 @@ if __name__ == "__main__":
m.load_map("input")
while m.step():
print(m.pos, m.direction)
if verbose:
print(m.pos, m.direction)
#m.show()
print(len(m.trace), m.trace)
#print(len(m.trace), m.trace)
print(len(set(m.trace)))

28
2024/06/part2.py Normal file
View File

@ -0,0 +1,28 @@
from part1 import *
thoughts = \
"""
So, we can place an obstacle on each of the 130*130 - #obstacles = 16900
- obstacles positions, but the initial path only covers 1512 positions
(thus 1512 - 1 = 1511 steps). By instead placing an obstacle on each of
those steps, we can find a loop.
The other thing we need to do, is detect loops. For that, It would be
nice to store both positions and directions to establish uniqueness,
or just check whether it is the fifth time in a position (as we have
then travelled to that position at least twice from at least one
position; see Pigeonhole principle).
"""
if __name__ == "__main__":
m = Map()
#m.load_map("testinput")
m.load_map("input")
while m.step():
# After each step, we can fork the map and add the obstacle.
print(m.pos, m.direction)
#m.show()
print(len(m.trace), m.trace)
print(len(set(m.trace)))