solved Day16 in python
This commit is contained in:
parent
b3b1e40b4e
commit
d654b246a3
99
Day16/README.md
Normal file
99
Day16/README.md
Normal file
@ -0,0 +1,99 @@
|
||||
# Day 16: The Floor Will Be Lava
|
||||
## Part One
|
||||
With the beam of light completely focused somewhere, the reindeer leads you deeper still into the Lava Production Facility. At some point, you realize that the steel facility walls have been replaced with cave, and the doorways are just cave, and the floor is cave, and you're pretty sure this is actually just a giant cave.
|
||||
|
||||
Finally, as you approach what must be the heart of the mountain, you see a bright light in a cavern up ahead. There, you discover that the beam of light you so carefully focused is emerging from the cavern wall closest to the facility and pouring all of its energy into a contraption on the opposite side.
|
||||
|
||||
Upon closer inspection, the contraption appears to be a flat, two-dimensional square grid containing empty space `(.)`, mirrors `(/` and `\)`, and splitters `(|` and `-)`.
|
||||
|
||||
The contraption is aligned so that most of the beam bounces around the grid, but each tile on the grid converts some of the beam's light into heat to melt the rock in the cavern.
|
||||
|
||||
You note the layout of the contraption (your puzzle input). For example:
|
||||
```
|
||||
.|...\....
|
||||
|.-.\.....
|
||||
.....|-...
|
||||
........|.
|
||||
..........
|
||||
.........\
|
||||
..../.\\..
|
||||
.-.-/..|..
|
||||
.|....-|.\
|
||||
..//.|....
|
||||
```
|
||||
|
||||
The beam enters in the top-left corner from the left and heading to the right. Then, its behavior depends on what it encounters as it moves:
|
||||
- If the beam encounters empty space `(.)`, it continues in the same direction.
|
||||
- If the beam encounters a mirror `(/` or `\)`, the beam is reflected 90 degrees depending on the angle of the mirror. For instance, a rightward-moving beam that encounters a `/` mirror would continue upward in the mirror's column, while a rightward-moving beam that encounters a `\` mirror would continue downward from the mirror's column.
|
||||
- If the beam encounters the pointy end of a splitter `(|` or `-)`, the beam passes through the splitter as if the splitter were empty space. For instance, a rightward-moving beam that encounters a `-` splitter would continue in the same direction.
|
||||
- If the beam encounters the flat side of a splitter `(|` or `-)`, the beam is split into two beams going in each of the two directions the splitter's pointy ends are pointing. For instance, a rightward-moving beam that encounters a `|` splitter would split into two beams: one that continues upward from the splitter's column and one that continues downward from the splitter's column.
|
||||
|
||||
Beams do not interact with other beams; a tile can have many beams passing through it at the same time. A tile is energized if that tile has at least one beam pass through it, reflect in it, or split in it.
|
||||
|
||||
In the above example, here is how the beam of light bounces around the contraption:
|
||||
```
|
||||
>|<<<\....
|
||||
|v-.\^....
|
||||
.v...|->>>
|
||||
.v...v^.|.
|
||||
.v...v^...
|
||||
.v...v^..\
|
||||
.v../2\\..
|
||||
<->-/vv|..
|
||||
.|<<<2-|.\
|
||||
.v//.|.v..
|
||||
```
|
||||
|
||||
Beams are only shown on empty tiles; arrows indicate the direction of the beams. If a tile contains beams moving in multiple directions, the number of distinct directions is shown instead. Here is the same diagram but instead only showing whether a tile is energized `(#)` or not `(.)`:
|
||||
```
|
||||
######....
|
||||
.#...#....
|
||||
.#...#####
|
||||
.#...##...
|
||||
.#...##...
|
||||
.#...##...
|
||||
.#..####..
|
||||
########..
|
||||
.#######..
|
||||
.#...#.#..
|
||||
```
|
||||
|
||||
Ultimately, in this example, 46 tiles become energized.
|
||||
|
||||
The light isn't energizing enough tiles to produce lava; to debug the contraption, you need to start by analyzing the current situation. With the beam starting in the top-left heading right, how many tiles end up being energized?
|
||||
|
||||
## Part Two
|
||||
As you try to work out what might be wrong, the reindeer tugs on your shirt and leads you to a nearby control panel. There, a collection of buttons lets you align the contraption so that the beam enters from any edge tile and heading away from that edge. (You can choose either of two directions for the beam if it starts on a corner; for instance, if the beam starts in the bottom-right corner, it can start heading either left or upward.)
|
||||
|
||||
So, the beam could start on any tile in the top row (heading downward), any tile in the bottom row (heading upward), any tile in the leftmost column (heading right), or any tile in the rightmost column (heading left). To produce lava, you need to find the configuration that energizes as many tiles as possible.
|
||||
|
||||
In the above example, this can be achieved by starting the beam in the fourth tile from the left in the top row:
|
||||
|
||||
```
|
||||
.|<2<\....
|
||||
|v-v\^....
|
||||
.v.v.|->>>
|
||||
.v.v.v^.|.
|
||||
.v.v.v^...
|
||||
.v.v.v^..\
|
||||
.v.v/2\\..
|
||||
<-2-/vv|..
|
||||
.|<<<2-|.\
|
||||
.v//.|.v..
|
||||
```
|
||||
|
||||
Using this configuration, 51 tiles are energized:
|
||||
```
|
||||
.#####....
|
||||
.#.#.#....
|
||||
.#.#.#####
|
||||
.#.#.##...
|
||||
.#.#.##...
|
||||
.#.#.##...
|
||||
.#.#####..
|
||||
########..
|
||||
.#######..
|
||||
.#...#.#..
|
||||
```
|
||||
|
||||
Find the initial beam configuration that energizes the largest number of tiles; how many tiles are energized in that configuration?
|
84
Day16/python/solution1.py
Normal file
84
Day16/python/solution1.py
Normal file
@ -0,0 +1,84 @@
|
||||
import sys
|
||||
|
||||
|
||||
def read_grid(file_path):
|
||||
"""Reads the grid from a file."""
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
return [list(line.strip()) for line in file.readlines()]
|
||||
except FileNotFoundError:
|
||||
print(f"Error: File '{file_path}' not found.")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"Error reading file '{file_path}': {e}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def step(r, c, d, DR, DC):
|
||||
"""Calculates the next position and direction of the beam."""
|
||||
return (r + DR[d], c + DC[d], d)
|
||||
|
||||
|
||||
def score(G, sr, sc, sd, DR, DC):
|
||||
"""Calculates the number of unique tiles energized by the beam."""
|
||||
POS = [(sr, sc, sd)]
|
||||
SEEN = set()
|
||||
SEEN2 = set()
|
||||
while POS:
|
||||
NP = []
|
||||
for r, c, d in POS:
|
||||
if 0 <= r < len(G) and 0 <= c < len(G[0]):
|
||||
SEEN.add((r, c))
|
||||
if (r, c, d) in SEEN2:
|
||||
continue
|
||||
SEEN2.add((r, c, d))
|
||||
ch = G[r][c]
|
||||
if ch == ".":
|
||||
NP.append(step(r, c, d, DR, DC))
|
||||
elif ch == "/":
|
||||
NP.append(step(r, c, {0: 1, 1: 0, 2: 3, 3: 2}[d], DR, DC))
|
||||
elif ch == "\\":
|
||||
NP.append(step(r, c, {0: 3, 1: 2, 2: 1, 3: 0}[d], DR, DC))
|
||||
elif ch == "|":
|
||||
if d in [0, 2]:
|
||||
NP.append(step(r, c, d, DR, DC))
|
||||
else:
|
||||
NP.append(step(r, c, 0, DR, DC))
|
||||
NP.append(step(r, c, 2, DR, DC))
|
||||
elif ch == "-":
|
||||
if d in [1, 3]:
|
||||
NP.append(step(r, c, d, DR, DC))
|
||||
else:
|
||||
NP.append(step(r, c, 1, DR, DC))
|
||||
NP.append(step(r, c, 3, DR, DC))
|
||||
else:
|
||||
assert False, f"Invalid character '{ch}' in grid."
|
||||
POS = NP
|
||||
return len(SEEN)
|
||||
|
||||
|
||||
def test():
|
||||
"""Test function to verify the implementation with test data."""
|
||||
G = read_grid("../test.txt")
|
||||
DR = [-1, 0, 1, 0]
|
||||
DC = [0, 1, 0, -1]
|
||||
result = score(G, 0, 0, 1, DR, DC)
|
||||
expected_result = 46 # Change this to the expected result of your test
|
||||
assert (
|
||||
result == expected_result
|
||||
), f"Test failed: Expected {expected_result}, got {result}"
|
||||
print("Test passed.")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to run the algorithm with actual puzzle input."""
|
||||
test() # Run test first
|
||||
G = read_grid("../input.txt")
|
||||
DR = [-1, 0, 1, 0]
|
||||
DC = [0, 1, 0, -1]
|
||||
result = score(G, 0, 0, 1, DR, DC)
|
||||
print(f"Number of tiles energized: {result}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
111
Day16/python/solution2.py
Normal file
111
Day16/python/solution2.py
Normal file
@ -0,0 +1,111 @@
|
||||
import sys
|
||||
|
||||
|
||||
def read_grid(file_path):
|
||||
"""Reads the grid from a file."""
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
return [list(line.strip()) for line in file.readlines()]
|
||||
except FileNotFoundError:
|
||||
print(f"Error: File '{file_path}' not found.")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"Error reading file '{file_path}': {e}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def step(r, c, d, DR, DC):
|
||||
"""Calculates the next position and direction of the beam."""
|
||||
return (r + DR[d], c + DC[d], d)
|
||||
|
||||
|
||||
def score(G, sr, sc, sd, DR, DC):
|
||||
"""Calculates the number of unique tiles energized by the beam."""
|
||||
POS = [(sr, sc, sd)]
|
||||
SEEN = set()
|
||||
SEEN2 = set()
|
||||
while POS:
|
||||
NP = []
|
||||
for r, c, d in POS:
|
||||
if 0 <= r < len(G) and 0 <= c < len(G[0]):
|
||||
SEEN.add((r, c))
|
||||
if (r, c, d) in SEEN2:
|
||||
continue
|
||||
SEEN2.add((r, c, d))
|
||||
ch = G[r][c]
|
||||
if ch == ".":
|
||||
NP.append(step(r, c, d, DR, DC))
|
||||
elif ch == "/":
|
||||
NP.append(step(r, c, {0: 1, 1: 0, 2: 3, 3: 2}[d], DR, DC))
|
||||
elif ch == "\\":
|
||||
NP.append(step(r, c, {0: 3, 1: 2, 2: 1, 3: 0}[d], DR, DC))
|
||||
elif ch == "|":
|
||||
if d in [0, 2]:
|
||||
NP.append(step(r, c, d, DR, DC))
|
||||
else:
|
||||
NP.append(step(r, c, 0, DR, DC))
|
||||
NP.append(step(r, c, 2, DR, DC))
|
||||
elif ch == "-":
|
||||
if d in [1, 3]:
|
||||
NP.append(step(r, c, d, DR, DC))
|
||||
else:
|
||||
NP.append(step(r, c, 1, DR, DC))
|
||||
NP.append(step(r, c, 3, DR, DC))
|
||||
else:
|
||||
assert False, f"Invalid character '{ch}' in grid."
|
||||
POS = NP
|
||||
return len(SEEN)
|
||||
|
||||
|
||||
def find_best_configuration(G, DR, DC):
|
||||
"""Finds the configuration that energizes the most tiles."""
|
||||
max_energized = 0
|
||||
for r in range(len(G)):
|
||||
for c in range(len(G[0])):
|
||||
if r == 0: # Top row, beam enters downward
|
||||
energized = score(G, r, c, 2, DR, DC)
|
||||
max_energized = max(max_energized, energized)
|
||||
elif r == len(G) - 1: # Bottom row, beam enters upward
|
||||
energized = score(G, r, c, 0, DR, DC)
|
||||
max_energized = max(max_energized, energized)
|
||||
if c == 0: # Leftmost column, beam enters rightward
|
||||
energized = score(G, r, c, 1, DR, DC)
|
||||
max_energized = max(max_energized, energized)
|
||||
elif c == len(G[0]) - 1: # Rightmost column, beam enters leftward
|
||||
energized = score(G, r, c, 3, DR, DC)
|
||||
max_energized = max(max_energized, energized)
|
||||
return max_energized
|
||||
|
||||
|
||||
def test():
|
||||
"""Test function to verify the implementation with test data."""
|
||||
G = read_grid("../test.txt")
|
||||
DR = [-1, 0, 1, 0]
|
||||
DC = [0, 1, 0, -1]
|
||||
result = score(G, 0, 0, 1, DR, DC)
|
||||
expected_result = 46 # Change this to the expected result of your test
|
||||
assert (
|
||||
result == expected_result
|
||||
), f"Test failed: Expected {expected_result}, got {result}"
|
||||
|
||||
max_tiles_energized = find_best_configuration(G, DR, DC)
|
||||
expected_energized = 51
|
||||
assert (
|
||||
max_tiles_energized == expected_energized
|
||||
), f"Test failed: Expected {expected_energized}, got {max_tiles_energized}"
|
||||
|
||||
print("Test passed.")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to run the algorithm with actual puzzle input."""
|
||||
test() # Run test first
|
||||
G = read_grid("../input.txt")
|
||||
DR = [-1, 0, 1, 0]
|
||||
DC = [0, 1, 0, -1]
|
||||
max_tiles_energized = find_best_configuration(G, DR, DC)
|
||||
print(f"Maximum number of tiles energized: {max_tiles_energized}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
10
Day16/test.txt
Normal file
10
Day16/test.txt
Normal file
@ -0,0 +1,10 @@
|
||||
.|...\....
|
||||
|.-.\.....
|
||||
.....|-...
|
||||
........|.
|
||||
..........
|
||||
.........\
|
||||
..../.\\..
|
||||
.-.-/..|..
|
||||
.|....-|.\
|
||||
..//.|....
|
Loading…
Reference in New Issue
Block a user