Files
adventofcode/2024/06/part2.py
Kees van Kempen efe6e5a0c3 2024(6): attempt to troubleshoot slowness
It takes 10 - 20 minutes to solve it. It is too slow. It seems that
List.count takes too long.
2024-12-26 16:37:28 +01:00

66 lines
1.6 KiB
Python

from part1 import *
verbose = False
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")
# Prepare forked map for speed
forked_map = m.copy()
#forked_map = Map()
#forked_map.load_map("input")
begin_pos = m.pos
begin_direction = m.direction
loop_obstacles = []
i = 0
while m.step():
print(i)
if verbose:
print(m.pos, m.direction)
# Create a copy
#forked_map = m.copy()
#forked_map = Map()
#forked_map.load_map("input")
#forked_map.map = m.map.copy()
forked_map.map[m.next_pos()] = Map.Tiles.OBSTACLE.value
forked_map.map[m.pos] = m.map[m.pos]
forked_map.pos = begin_pos
forked_map.direction = begin_direction
forked_map.trace = [begin_pos]
print(f"Forking at {forked_map.next_pos()}... ", end="")
try:
while forked_map.step():
continue
except Map.LoopException:
print("loop.")
loop_obstacles.append(m.next_pos())
else:
print("no loop.")
i += 1
if i > 100:
break
#m.show()
#print(len(m.trace), m.trace)
#print(len(set(m.trace)))
print(len(loop_obstacles))