some clean ups

This commit is contained in:
Heiko Ludwig 2024-12-08 09:16:54 +01:00
parent 5d48e673e1
commit 216dab2c4e

View file

@ -17,37 +17,50 @@ def get_lab(lines: list) -> tuple:
if cell_content == "^": if cell_content == "^":
g_row, g_col = row_num, col_num g_row, g_col = row_num, col_num
row.append('.') row.append('.')
else: row.append(cell_content) else:
row.append(cell_content)
lab.append(row) lab.append(row)
return lab, g_row, g_col return lab, g_row, g_col
def next_position(row: int, col: int, direction: int) -> tuple:
deltas = [(-1, 0), (0, 1), (1, 0), (0, -1)]
delta_row, delta_col = deltas[direction]
new_row = row + delta_row
new_col = col + delta_col
return new_row, new_col
def pos_invalid(row, col, max_row, max_col) -> bool:
if 0 <= row <= max_row and 0 <= col <= max_col:
return False
return True
def get_visits(lab: list, g_row: int, g_col: int) -> int: def get_visits(lab: list, g_row: int, g_col: int) -> int:
visits = {} visits = {}
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
g_dir = 0 g_dir = 0
max_row = len(lab) - 1
max_col = len(lab[0]) - 1
while True: while True:
visits[g_row,g_col] = True new_row, new_col = next_position(g_row, g_col, g_dir)
delta_row, delta_col = directions[g_dir] visits[g_row, g_col] = True
new_row = g_row + delta_row if pos_invalid(new_row, new_col, max_row, max_col):
new_col = g_col + delta_col
# print(new_row, new_col)
if new_row < 0 or new_row >= len(lab) or new_col < 0 or new_col >= len(lab[0]):
return len(visits) return len(visits)
elif lab[new_row][new_col] == "#": elif lab[new_row][new_col] == "#":
g_dir += 1 g_dir = (g_dir + 1) % 4
if g_dir >= len(directions):
g_dir = 0
else: else:
g_row = new_row g_row = new_row
g_col = new_col g_col = new_col
def main(): def main():
# lines = get_lines("sample-input.txt") # lines = get_lines("sample-input.txt")
lines = get_lines("input.txt") lines = get_lines("input.txt")
lab, g_row, g_col = get_lab(lines) lab, g_row, g_col = get_lab(lines)
# print(lab) visits = get_visits(lab, g_row, g_col)
# print(g_row, g_col) print("Part 1: Visited positions:", visits)
print("Part 1: Visited positions:", get_visits(lab, g_row, g_col))
if __name__ == '__main__': if __name__ == '__main__':
main() main()