solved Day18 in python

This commit is contained in:
WieErWill 2023-12-18 17:49:47 +01:00
parent d654b246a3
commit 776c74fc1e
4 changed files with 265 additions and 0 deletions

85
Day18/README.md Normal file
View File

@ -0,0 +1,85 @@
# Day 18: Lavaduct Lagoon
## Part One
Thanks to your efforts, the machine parts factory is one of the first factories up and running since the lavafall came back. However, to catch up with the large backlog of parts requests, the factory will also need a large supply of lava for a while; the Elves have already started creating a large lagoon nearby for this purpose.
However, they aren't sure the lagoon will be big enough; they've asked you to take a look at the dig plan (your puzzle input). For example:
```
R 6 (#70c710)
D 5 (#0dc571)
L 2 (#5713f0)
D 2 (#d2c081)
R 2 (#59c680)
D 2 (#411b91)
L 5 (#8ceee2)
U 2 (#caa173)
L 1 (#1b58a2)
U 2 (#caa171)
R 2 (#7807d2)
U 3 (#a77fa3)
L 2 (#015232)
U 2 (#7a21e3)
```
The digger starts in a 1 meter cube hole in the ground. They then dig the specified number of meters up (U), down (D), left (L), or right (R), clearing full 1 meter cubes as they go. The directions are given as seen from above, so if "up" were north, then "right" would be east, and so on. Each trench is also listed with the color that the edge of the trench should be painted as an RGB hexadecimal color code.
When viewed from above, the above example dig plan would result in the following loop of trench (#) having been dug out from otherwise ground-level terrain (.):
```
#######
#.....#
###...#
..#...#
..#...#
###.###
#...#..
##..###
.#....#
.######
```
At this point, the trench could contain 38 cubic meters of lava. However, this is just the edge of the lagoon; the next step is to dig out the interior so that it is one meter deep as well:
```
#######
#######
#######
..#####
..#####
#######
#####..
#######
.######
.######
```
Now, the lagoon can contain a much more respectable 62 cubic meters of lava. While the interior is dug out, the edges are also painted according to the color codes in the dig plan.
The Elves are concerned the lagoon won't be large enough; if they follow their dig plan, how many cubic meters of lava could it hold?
## Part Two
The Elves were right to be concerned; the planned lagoon would be much too small.
After a few minutes, someone realizes what happened; someone swapped the color and instruction parameters when producing the dig plan. They don't have time to fix the bug; one of them asks if you can extract the correct instructions from the hexadecimal codes.
Each hexadecimal code is six hexadecimal digits long. The first five hexadecimal digits encode the distance in meters as a five-digit hexadecimal number. The last hexadecimal digit encodes the direction to dig: 0 means R, 1 means D, 2 means L, and 3 means U.
So, in the above example, the hexadecimal codes can be converted into the true instructions:
- #70c710 = R 461937
- #0dc571 = D 56407
- #5713f0 = R 356671
- #d2c081 = D 863240
- #59c680 = R 367720
- #411b91 = D 266681
- #8ceee2 = L 577262
- #caa173 = U 829975
- #1b58a2 = L 112010
- #caa171 = D 829975
- #7807d2 = L 491645
- #a77fa3 = U 686074
- #015232 = L 5411
- #7a21e3 = U 500254
Digging out this loop and its interior produces a lagoon that can hold an impressive 952408144115 cubic meters of lava.
Convert the hexadecimal color codes into the correct instructions; if the Elves follow this new dig plan, how many cubic meters of lava could the lagoon hold?

101
Day18/python/solution1.py Normal file
View File

@ -0,0 +1,101 @@
def parse_instructions(file_path):
"""Parse instructions from the given file."""
try:
with open(file_path, 'r') as file:
instructions = [line.strip().split() for line in file.readlines()]
print(f"Parsed {len(instructions)} instructions from {file_path}")
return instructions
except Exception as e:
print(f"Error reading file {file_path}: {e}")
raise
def apply_instruction(grid, position, direction, steps):
"""Apply a single instruction to the grid and update the position."""
deltas = {'U': (0, -1), 'D': (0, 1), 'L': (-1, 0), 'R': (1, 0)}
dx, dy = deltas[direction]
for _ in range(steps):
position = (position[0] + dx, position[1] + dy)
grid.add(position)
#print(f"Moved {direction} to {position}")
return position
def create_path(instructions):
"""Create the path based on the instructions."""
grid = set()
position = (0, 0)
grid.add(position)
for instruction in instructions:
direction, steps = instruction[0], int(instruction[1])
print(f"Applying instruction: {direction} {steps}")
position = apply_instruction(grid, position, direction, steps)
return grid
def flood_fill(grid, bounds):
"""Perform flood-fill to find cells outside the path."""
filled = set()
to_fill = [(bounds[0], y) for y in range(bounds[2], bounds[3] + 1)] \
+ [(bounds[1], y) for y in range(bounds[2], bounds[3] + 1)] \
+ [(x, bounds[2]) for x in range(bounds[0], bounds[1] + 1)] \
+ [(x, bounds[3]) for x in range(bounds[0], bounds[1] + 1)]
while to_fill:
x, y = to_fill.pop()
if (x, y) in filled or (x, y) in grid:
continue
filled.add((x, y))
if x > bounds[0]: to_fill.append((x - 1, y))
if x < bounds[1]: to_fill.append((x + 1, y))
if y > bounds[2]: to_fill.append((x, y - 1))
if y < bounds[3]: to_fill.append((x, y + 1))
return filled
def calculate_area(grid):
"""Calculate the area inside the loop."""
min_x = min(grid, key=lambda x: x[0])[0]
max_x = max(grid, key=lambda x: x[0])[0]
min_y = min(grid, key=lambda x: x[1])[1]
max_y = max(grid, key=lambda x: x[1])[1]
bounds = (min_x, max_x, min_y, max_y)
outside_area = flood_fill(grid, bounds)
total_area = (max_x - min_x + 1) * (max_y - min_y + 1)
inside_area = total_area - len(outside_area)
return inside_area
def run_test(test_file):
"""Run the algorithm with test input."""
try:
instructions = parse_instructions(test_file)
grid = create_path(instructions)
area = calculate_area(grid)
assert area == 62, f"Test failed. Expected 62 but got {area} with grid {grid}"
print("Test passed successfully.")
return True
except AssertionError as e:
print(f"Assertion Error: {e}")
return False
def main():
"""Main function to run the puzzle solution."""
test_file = "../test.txt"
input_file = "../input.txt"
# Run test
if run_test(test_file):
# Process actual puzzle input
try:
instructions = parse_instructions(input_file)
grid = create_path(instructions)
area = calculate_area(grid)
print(f"Puzzle result (area): {area}")
except Exception as e:
print(f"Error during puzzle execution: {e}")
else:
print("Test failed. Halting execution.")
if __name__ == "__main__":
main()

65
Day18/python/solution2.py Normal file
View File

@ -0,0 +1,65 @@
def parse_instructions(file_path):
"""Parse instructions from the given file."""
try:
with open(file_path, 'r') as file:
lines = file.read().splitlines()
print(f"Parsed {len(lines)} instructions from {file_path}")
return lines
except Exception as e:
print(f"Error reading file {file_path}: {e}")
raise
def calculate_area(lines):
"""Calculate the area inside the loop defined by the instructions."""
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
points = [(0, 0)]
boundary = 0
for line in lines:
*_, color = line.split()
instructions = color[2:-1]
dr, dc = DIRECTIONS[int(instructions[-1])]
steps = int(instructions[:-1], 16)
boundary += steps
row, column = points[-1]
points.append((row + dr * steps, column + dc * steps))
area = abs(
sum(x1 * y2 - x2 * y1 for (x1, y1), (x2, y2) in zip(points, points[1:] + points[:1]))
) // 2 + boundary // 2 + 1
return area
def run_test(test_file, expected_result):
"""Run the algorithm with test input and compare with the expected result."""
try:
lines = parse_instructions(test_file)
calculated_area = calculate_area(lines)
assert calculated_area == expected_result, f"Test failed, expected {expected_result}, got {calculated_area}"
print(f"Test passed, area: {calculated_area}")
except AssertionError as e:
print(e)
raise
except Exception as e:
print(f"Error during test execution: {e}")
raise
def main():
"""Main function to run the puzzle solution."""
test_file = "../test.txt"
input_file = "../input.txt"
expected_test_area = 952408144115 # Replace with the correct expected area for the test
# Run test
try:
run_test(test_file, expected_test_area)
# Process actual puzzle input
lines = parse_instructions(input_file)
area = calculate_area(lines)
print(f"Puzzle result (area): {area}")
except Exception as e:
print(f"Execution halted due to error: {e}")
if __name__ == "__main__":
main()

14
Day18/test.txt Normal file
View File

@ -0,0 +1,14 @@
R 6 (#70c710)
D 5 (#0dc571)
L 2 (#5713f0)
D 2 (#d2c081)
R 2 (#59c680)
D 2 (#411b91)
L 5 (#8ceee2)
U 2 (#caa173)
L 1 (#1b58a2)
U 2 (#caa171)
R 2 (#7807d2)
U 3 (#a77fa3)
L 2 (#015232)
U 2 (#7a21e3)