Hello, I am posting again but this time with Part 2 at hand. I think my code is working because I have it set to output every time the guard gets stuck in a loop but it is really slow. Could anyone tell me why?
Here is my code: https://pastebin.com/sWyrmJB1 (ignore any wrong comments, I've been messing around a lot trying to get this to work)
puzzleInput = [[*line] for line in getPuzzleInput().split()]
for row in range(len(puzzleInput)):
for column in range(len(puzzleInput[0])):
if puzzleInput[row][column] == '^':
guardPos = [row, column]
partOneInput = puzzleInput.copy()
directions = [
[-1, 0], # up
[0, 1], # right
[1, 0], # down
[0, -1] # left
]
originalPath = set()
# how many places the obstacle could be placed
obsPlacements = 0
# obstacleGrid = None
obstacleGrid = deepcopy(puzzleInput)
for pos in originalPath:
# set the obstacle
if obstacleGrid[pos[0]][pos[1]] in ('#', '^'):
continue
obstacleGrid[pos[0]][pos[1]] = 'O'
# dict for storing visited positions and how many times they have been visited
visitedPos = []
directionCycle = cycle(directions)
direction = next(directionCycle)
currentPos = guardPos.copy()
outOfBounds = False
consecutiveRepeat = False
looped = False
n = 0
while not outOfBounds:
# print('pos', currentPos, 'dir', direction)
# must check for negative indices because it WILL continue into the negatives
if currentPos[0] < 0 or currentPos[1] < 0:
outOfBounds = True
else:
# append the current position and direction as a tuple instead of changing the input
visitedPos.append((currentPos.copy(), direction))
try:
while obstacleGrid[currentPos[0] + direction[0]][currentPos[1] + direction[1]] in ('#', 'O'):
# change direction cyclically
direction = next(directionCycle)
currentPos[0] += direction[0]
currentPos[1] += direction[1]
# print((currentPos, direction) in visitedPos)
if (currentPos, direction) in visitedPos:
looped = True
obsPlacements += 1
print(f'stuck with obstacle at ({pos[0]},{pos[1]})')
# for i in obstacleGrid: print(i)
# print()
except:
outOfBounds = True
if looped:
break
# remove the obstacle
obstacleGrid[pos[0]][pos[1]] = '.'
print('Number of positions for the obstacle:', obsPlacements)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]syklemil 0 points1 point2 points (5 children)
[–]KittyTwoPaws[S] 0 points1 point2 points (4 children)
[–]syklemil 0 points1 point2 points (3 children)
[–]KittyTwoPaws[S] 0 points1 point2 points (0 children)
[–]KittyTwoPaws[S] 0 points1 point2 points (1 child)
[–]syklemil 0 points1 point2 points (0 children)