From 21f5c917429d9ff9507761ad43200a38d8a7e501 Mon Sep 17 00:00:00 2001 From: FrederikBaerentsen Date: Fri, 6 Dec 2024 22:56:55 +0100 Subject: [PATCH] Optimized 2024/06 P2 --- 2024/06/solution.py | 46 +++++++++++++++++++++++++++------------------ 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/2024/06/solution.py b/2024/06/solution.py index c49ef8d..2351a11 100644 --- a/2024/06/solution.py +++ b/2024/06/solution.py @@ -77,20 +77,32 @@ if part == 2: def isLoop(grid,pos,direction): positions = [] - - while grid_valid(pos[0],pos[1],grid): - #nprint(grid,pos,'X') - if get_value_in_direction(grid,pos,direction) != '#': - cur = (pos[0],pos[1],direction) + count = 0 + l = len(grid) - if cur not in positions: - positions.append(cur) - else: - return 1 - pos = (pos[0]+offsets[direction][0],pos[1]+offsets[direction][1]) - elif get_value_in_direction(grid,pos,direction) == '#': + while grid_valid(pos[0],pos[1],grid): + next = get_value_in_direction(grid,pos,direction) + if next == '#': direction = next_direction[direction] - #input() + else: + cur = (pos[0],pos[1],direction) + count += 1 + + # Instead of loging all visited positions and their direction, + # we can break out if we have visited more places than 4x the + # grid size (4 being once for each direction). + # This actually gives us the right result + + #if cur not in positions: + # positions.append(cur) + #elif cur in positions: + # return 1 + + if count > 4*l*l: + return 1 + + pos = (pos[0]+offsets[direction][0],pos[1]+offsets[direction][1]) + return 0 grid = toGrid(input_f) @@ -105,7 +117,6 @@ if part == 2: pos = start while grid_valid(pos[0],pos[1],grid): - dir = get_value_in_direction(grid, pos) if get_value_in_direction(grid,pos,direction) != '#': if pos not in steps: @@ -115,11 +126,10 @@ if part == 2: direction = next_direction[direction] steps.remove(start) print(len(steps)) + result = 0 for idx,i in enumerate(steps): - print(idx) - new_grid = grid[:] - new_grid[i[0]][i[1]] = '#' - result += isLoop(new_grid,start,'up') - new_grid[i[0]][i[1]] = '.' + grid[i[0]][i[1]] = '#' + result += isLoop(grid,start,'up') + grid[i[0]][i[1]] = '.' print(result) \ No newline at end of file