starting Day10
This commit is contained in:
parent
2e8e5537a0
commit
7aba5cf373
103
Day10/README.md
Normal file
103
Day10/README.md
Normal file
@ -0,0 +1,103 @@
|
||||
# Day 10: Pipe Maze
|
||||
## Day One
|
||||
You use the hang glider to ride the hot air from Desert Island all the way up to the floating metal island. This island is surprisingly cold and there definitely aren't any thermals to glide on, so you leave your hang glider behind.
|
||||
|
||||
You wander around for a while, but you don't find any people or animals. However, you do occasionally find signposts labeled "Hot Springs" pointing in a seemingly consistent direction; maybe you can find someone at the hot springs and ask them where the desert-machine parts are made.
|
||||
|
||||
The landscape here is alien; even the flowers and trees are made of metal. As you stop to admire some metal grass, you notice something metallic scurry away in your peripheral vision and jump into a big pipe! It didn't look like any animal you've ever seen; if you want a better look, you'll need to get ahead of it.
|
||||
|
||||
Scanning the area, you discover that the entire field you're standing on is densely packed with pipes; it was hard to tell at first because they're the same metallic silver color as the "ground". You make a quick sketch of all of the surface pipes you can see (your puzzle input).
|
||||
|
||||
The pipes are arranged in a two-dimensional grid of tiles:
|
||||
- `|` is a vertical pipe connecting north and south.
|
||||
- `-` is a horizontal pipe connecting east and west.
|
||||
- `L` is a 90-degree bend connecting north and east.
|
||||
- `J` is a 90-degree bend connecting north and west.
|
||||
- `7` is a 90-degree bend connecting south and west.
|
||||
- `F` is a 90-degree bend connecting south and east.
|
||||
- `.` is ground; there is no pipe in this tile.
|
||||
- `S` is the starting position of the animal; there is a pipe on this tile, but your sketch doesn't show what shape the pipe has.
|
||||
|
||||
Based on the acoustics of the animal's scurrying, you're confident the pipe that contains the animal is one large, continuous loop.
|
||||
|
||||
For example, here is a square loop of pipe:
|
||||
```
|
||||
.....
|
||||
.F-7.
|
||||
.|.|.
|
||||
.L-J.
|
||||
.....
|
||||
```
|
||||
If the animal had entered this loop in the northwest corner, the sketch would instead look like this:
|
||||
```
|
||||
.....
|
||||
.S-7.
|
||||
.|.|.
|
||||
.L-J.
|
||||
.....
|
||||
```
|
||||
In the above diagram, the S tile is still a 90-degree F bend: you can tell because of how the adjacent pipes connect to it.
|
||||
|
||||
Unfortunately, there are also many pipes that aren't connected to the loop! This sketch shows the same loop as above:
|
||||
```
|
||||
-L|F7
|
||||
7S-7|
|
||||
L|7||
|
||||
-L-J|
|
||||
L|-JF
|
||||
```
|
||||
In the above diagram, you can still figure out which pipes form the main loop: they're the ones connected to S, pipes those pipes connect to, pipes those pipes connect to, and so on. Every pipe in the main loop connects to its two neighbors (including S, which will have exactly two pipes connecting to it, and which is assumed to connect back to those two pipes).
|
||||
|
||||
Here is a sketch that contains a slightly more complex main loop:
|
||||
```
|
||||
..F7.
|
||||
.FJ|.
|
||||
SJ.L7
|
||||
|F--J
|
||||
LJ...
|
||||
```
|
||||
Here's the same example sketch with the extra, non-main-loop pipe tiles also shown:
|
||||
```
|
||||
7-F7-
|
||||
.FJ|7
|
||||
SJLL7
|
||||
|F--J
|
||||
LJ.LJ
|
||||
```
|
||||
If you want to get out ahead of the animal, you should find the tile in the loop that is farthest from the starting position. Because the animal is in the pipe, it doesn't make sense to measure this by direct distance. Instead, you need to find the tile that would take the longest number of steps along the loop to reach from the starting point - regardless of which way around the loop the animal went.
|
||||
|
||||
In the first example with the square loop:
|
||||
```
|
||||
.....
|
||||
.S-7.
|
||||
.|.|.
|
||||
.L-J.
|
||||
.....
|
||||
```
|
||||
You can count the distance each tile in the loop is from the starting point like this:
|
||||
```
|
||||
.....
|
||||
.012.
|
||||
.1.3.
|
||||
.234.
|
||||
.....
|
||||
```
|
||||
In this example, the farthest point from the start is 4 steps away.
|
||||
|
||||
Here's the more complex loop again:
|
||||
```
|
||||
..F7.
|
||||
.FJ|.
|
||||
SJ.L7
|
||||
|F--J
|
||||
LJ...
|
||||
```
|
||||
Here are the distances for each tile on that loop:
|
||||
```
|
||||
..45.
|
||||
.236.
|
||||
01.78
|
||||
14567
|
||||
23...
|
||||
```
|
||||
Find the single giant loop starting at S. How many steps along the loop does it take to get from the starting position to the point farthest from the starting position?
|
102
Day10/python/solution1.py
Normal file
102
Day10/python/solution1.py
Normal file
@ -0,0 +1,102 @@
|
||||
def parse_grid(file_path):
|
||||
"""Parses the grid from a file and returns it as a 2D list."""
|
||||
try:
|
||||
with open(file_path, 'r') as file:
|
||||
grid = [list(line.strip()) for line in file]
|
||||
print(f"Grid parsed from {file_path}:")
|
||||
[print(''.join(row)) for row in grid]
|
||||
return grid
|
||||
except Exception as e:
|
||||
print(f"Error reading file {file_path}: {e}")
|
||||
raise
|
||||
|
||||
def create_graph(grid):
|
||||
"""Creates a graph from the grid."""
|
||||
graph = {}
|
||||
rows, cols = len(grid), len(grid[0])
|
||||
for r in range(rows):
|
||||
for c in range(cols):
|
||||
if grid[r][c] in "|-LJ7FS":
|
||||
graph[(r, c)] = get_neighbors(grid, r, c)
|
||||
print("Graph created from grid:")
|
||||
print(graph)
|
||||
return graph
|
||||
|
||||
def get_neighbors(grid, r, c):
|
||||
"""Finds the neighbors of a cell in the grid."""
|
||||
neighbors = []
|
||||
rows, cols = len(grid), len(grid[0])
|
||||
|
||||
# Directions: North, East, South, West
|
||||
directions = [(r-1, c), (r, c+1), (r+1, c), (r, c-1)]
|
||||
connected = {
|
||||
"|": [0, 2], "-": [1, 3],
|
||||
"L": [0, 1], "J": [0, 3],
|
||||
"7": [2, 3], "F": [1, 2],
|
||||
"S": [0, 1, 2, 3] # 'S' connects in all directions for initial identification
|
||||
}
|
||||
|
||||
for i, (dr, dc) in enumerate(directions):
|
||||
if 0 <= dr < rows and 0 <= dc < cols and grid[dr][dc] != '.':
|
||||
neighbor_type = grid[dr][dc]
|
||||
# Check if there is a valid connection
|
||||
if neighbor_type in connected:
|
||||
if i in connected[grid[r][c]] and (3-i) in connected[neighbor_type]: # Check reverse direction
|
||||
neighbors.append((dr, dc))
|
||||
|
||||
print(f"Neighbors for ({r}, {c}): {neighbors}")
|
||||
return neighbors
|
||||
|
||||
def bfs(graph, start):
|
||||
"""Performs BFS on the graph and returns the maximum distance from the start."""
|
||||
visited = set()
|
||||
queue = [(start, 0)]
|
||||
max_distance = 0
|
||||
while queue:
|
||||
node, distance = queue.pop(0)
|
||||
if node != start or len(visited) == 0: # Allow revisiting start only initially
|
||||
visited.add(node)
|
||||
max_distance = max(max_distance, distance)
|
||||
print(f"Visited node: {node}, Distance: {distance}")
|
||||
for neighbor in graph[node]:
|
||||
if neighbor not in visited or (neighbor == start and len(visited) > 1):
|
||||
queue.append((neighbor, distance + 1))
|
||||
print(f"Maximum distance from start: {max_distance}")
|
||||
return max_distance
|
||||
|
||||
def find_start(grid):
|
||||
"""Finds the starting position 'S' in the grid."""
|
||||
for r, row in enumerate(grid):
|
||||
for c, cell in enumerate(row):
|
||||
if cell == 'S':
|
||||
print(f"Starting position found at: ({r}, {c})")
|
||||
return r, c
|
||||
raise ValueError("Starting position 'S' not found in the grid")
|
||||
|
||||
def run_test(file_path):
|
||||
"""Runs the algorithm on a test file and asserts the result."""
|
||||
print(f"Running test with file: {file_path}")
|
||||
grid = parse_grid(file_path)
|
||||
graph = create_graph(grid)
|
||||
start = find_start(grid)
|
||||
max_distance = bfs(graph, start)
|
||||
print(f"Max distance for test: {max_distance}")
|
||||
return max_distance
|
||||
|
||||
def main(file_path):
|
||||
"""Main function to run the algorithm on the input file."""
|
||||
print(f"Running main algorithm with file: {file_path}")
|
||||
grid = parse_grid(file_path)
|
||||
graph = create_graph(grid)
|
||||
start = find_start(grid)
|
||||
max_distance = bfs(graph, start)
|
||||
print(f"Max distance for input: {max_distance}")
|
||||
return max_distance
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_result = run_test("../test.txt")
|
||||
assert test_result == 8, f"Test failed: expected 8, got {test_result}"
|
||||
print(f"Test passed with {test_result}")
|
||||
|
||||
input_result = main("../input.txt")
|
||||
print(f"Result for input file: {input_result}")
|
5
Day10/test.txt
Normal file
5
Day10/test.txt
Normal file
@ -0,0 +1,5 @@
|
||||
7-F7-
|
||||
.FJ|7
|
||||
SJLL7
|
||||
|F--J
|
||||
LJ.LJ
|
Loading…
Reference in New Issue
Block a user