|
| 1 | +import multiprocessing as mp |
| 2 | + |
| 3 | +moves = ["^", ">", "v", "<"] |
| 4 | +rules = [(-1, 0), (0, 1), (1, 0), (0, -1)] |
| 5 | + |
| 6 | + |
| 7 | +def main(): |
| 8 | + lines, obstacles, starting_dir, starting_pos = read_input('input/6_2.txt') |
| 9 | + |
| 10 | + with mp.Pool(mp.cpu_count()) as pool: |
| 11 | + results = pool.starmap(check_position, [ |
| 12 | + (lines, obstacles, starting_dir, starting_pos, line_idx, pos_idx) |
| 13 | + for line_idx, line in enumerate(lines) |
| 14 | + for pos_idx, pos in enumerate(line) |
| 15 | + if (line_idx, pos_idx) not in obstacles and (line_idx, pos_idx) != starting_pos |
| 16 | + ]) |
| 17 | + |
| 18 | + loop_count = sum(results) |
| 19 | + print("Loop Count:", loop_count) |
| 20 | + |
| 21 | + |
| 22 | +def check_position(lines, obstacles, starting_dir, starting_pos, line_idx, pos_idx): |
| 23 | + current_pos = starting_pos |
| 24 | + current_dir = starting_dir |
| 25 | + already_visited = {(current_pos[0], current_pos[1], current_dir)} |
| 26 | + new_obstacle = (line_idx, pos_idx) |
| 27 | + |
| 28 | + while True: |
| 29 | + if is_at_border(current_pos, lines): |
| 30 | + return False |
| 31 | + |
| 32 | + rule = rules[current_dir] |
| 33 | + new_pos = (current_pos[0] + rule[0], current_pos[1] + rule[1]) |
| 34 | + |
| 35 | + if new_pos in obstacles or new_pos == new_obstacle: |
| 36 | + current_dir = (current_dir + 1) % 4 |
| 37 | + else: |
| 38 | + current_pos = new_pos |
| 39 | + |
| 40 | + current_pos_dir = (current_pos[0], current_pos[1], current_dir) |
| 41 | + if current_pos_dir in already_visited: |
| 42 | + return True |
| 43 | + already_visited.add(current_pos_dir) |
| 44 | + |
| 45 | + |
| 46 | +def is_at_border(pos, lines): |
| 47 | + return pos[0] == 0 or pos[0] == len(lines) - 1 or pos[1] == 0 or pos[1] == len(lines[0]) - 1 |
| 48 | + |
| 49 | + |
| 50 | +def read_input(file_path): |
| 51 | + with open(file_path) as f: |
| 52 | + lines = f.read().splitlines() |
| 53 | + |
| 54 | + obstacles = set() |
| 55 | + starting_pos = () |
| 56 | + starting_dir = -1 |
| 57 | + for line_idx, line in enumerate(lines): |
| 58 | + for pos_idx, pos in enumerate(line): |
| 59 | + if pos in moves: |
| 60 | + starting_dir = moves.index(pos) |
| 61 | + starting_pos = (line_idx, pos_idx) |
| 62 | + elif pos == "#": |
| 63 | + obstacles.add((line_idx, pos_idx)) |
| 64 | + |
| 65 | + return lines, obstacles, starting_dir, starting_pos |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + main() |
0 commit comments