add title image

This commit is contained in:
wieerwill 2023-12-12 17:36:28 +01:00
parent 2b97334a8d
commit bf97872f92
5 changed files with 44 additions and 11 deletions

View File

@ -4,7 +4,7 @@ def parse_grid(file_path):
grid = {}
start = None
try:
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
for y, line in enumerate(file.read().splitlines()):
for x, char in enumerate(line):
match char:
@ -22,7 +22,12 @@ def parse_grid(file_path):
grid[(y, x)] = {(y + 1, x), (y, x + 1)}
case "S":
start = (y, x)
grid[(y, x)] = {(y, x - 1), (y, x + 1), (y - 1, x), (y + 1, x)}
grid[(y, x)] = {
(y, x - 1),
(y, x + 1),
(y - 1, x),
(y + 1, x),
}
case _:
pass
@ -37,6 +42,7 @@ def parse_grid(file_path):
print(f"Error parsing grid: {str(e)}")
raise
def find_cycle(grid, start):
"""Finds all nodes in the cycle starting from the starting position."""
print(f"Finding cycle from start position: {start}")
@ -50,9 +56,10 @@ def find_cycle(grid, start):
queue.append(dst)
return seen
def bfs_distance(grid, start, target):
"""Performs BFS to find distance from start to target."""
#print(f"Calculating BFS distance from {start} to {target}")
# print(f"Calculating BFS distance from {start} to {target}")
queue = [(start, 0)]
visited = set()
while queue:
@ -65,6 +72,7 @@ def bfs_distance(grid, start, target):
queue.append((neighbor, distance + 1))
return -1
def find_longest_distance(grid, cycle, start):
"""Finds the longest distance from the start in the cycle."""
print("Finding longest distance from start in the cycle.")
@ -75,6 +83,7 @@ def find_longest_distance(grid, cycle, start):
max_distance = max(max_distance, distance)
return max_distance
def run(file_path):
"""Runs the entire algorithm for the given file path."""
print(f"Running algorithm for file: {file_path}")
@ -84,14 +93,18 @@ def run(file_path):
print(f"Longest distance: {longest_distance}")
return longest_distance
def test():
"""Test function to validate the algorithm with a test file."""
print("Starting test...")
expected_result = 8 # Expected result for the test file
result = run("../test.txt")
assert result == expected_result, f"Test failed: Expected {expected_result}, got {result}"
assert (
result == expected_result
), f"Test failed: Expected {expected_result}, got {result}"
print("Test passed successfully.")
def main():
"""Main function to run the test and then the algorithm for the input file."""
try:
@ -101,5 +114,6 @@ def main():
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
main()

View File

@ -63,4 +63,4 @@ def find_inside(grid, cycle):
input_grid, input_start = parse_grid(open("../input.txt").read().splitlines())
print(len(find_cycle(input_grid, input_start)) // 2)
print(find_inside(input_grid, find_cycle(input_grid, input_start)))
print(find_inside(input_grid, find_cycle(input_grid, input_start)))

View File

@ -1,23 +1,29 @@
import sys
def read_grid(file_path):
"""Reads the grid from the file and returns it as a 2D list."""
try:
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
return [list(line.strip()) for line in file]
except Exception as e:
print(f"Error reading file {file_path}: {e}")
sys.exit(1)
def find_empty_rows_and_cols(grid):
"""Finds empty rows and columns in the grid."""
empty_rows = [i for i, row in enumerate(grid) if '#' not in row]
empty_cols = [j for j in range(len(grid[0])) if all(row[j] == '.' for row in grid)]
empty_rows = [i for i, row in enumerate(grid) if "#" not in row]
empty_cols = [j for j in range(len(grid[0])) if all(row[j] == "." for row in grid)]
return empty_rows, empty_cols
def locate_galaxies(grid):
"""Locates the coordinates of galaxies in the grid."""
return [(r, c) for r, row in enumerate(grid) for c, val in enumerate(row) if val == '#']
return [
(r, c) for r, row in enumerate(grid) for c, val in enumerate(row) if val == "#"
]
def calculate_distances(grid, galaxies, expansion_factor):
"""Calculates the sum of distances between all pairs of galaxies."""
@ -27,12 +33,21 @@ def calculate_distances(grid, galaxies, expansion_factor):
for i, (r1, c1) in enumerate(galaxies):
for r2, c2 in galaxies[i:]:
distance = abs(r2 - r1) + abs(c2 - c1)
distance += sum(expansion_factor for er in empty_rows if min(r1, r2) <= er <= max(r1, r2))
distance += sum(expansion_factor for ec in empty_cols if min(c1, c2) <= ec <= max(c1, c2))
distance += sum(
expansion_factor
for er in empty_rows
if min(r1, r2) <= er <= max(r1, r2)
)
distance += sum(
expansion_factor
for ec in empty_cols
if min(c1, c2) <= ec <= max(c1, c2)
)
total_distance += distance
return total_distance
def run_test():
"""Runs the test using the test file."""
test_grid = read_grid("../test.txt")
@ -41,6 +56,7 @@ def run_test():
assert test_result == 374, f"Test failed: Expected 374, got {test_result}"
print("Test passed successfully.")
def main():
print("Starting puzzle solution...")
@ -53,6 +69,7 @@ def main():
total_distance = calculate_distances(grid, galaxies, expansion_factor)
print(f"Total distance for part {'2' if part2 else '1'}: {total_distance}")
if __name__ == "__main__":
run_test()
main()

View File

@ -1,5 +1,7 @@
# 🎄 Advent of Code 2023 🎄
<div><img src="title_image.png" style="margin: 0 auto;" height="300" width="300" ></div>
![Build Status](https://github.com/wieerwill/advent_of_code_2023/actions/workflows/lint.yml/badge.svg)
![Completed](https://img.shields.io/badge/days%20completed-11-red)
![Stars](https://img.shields.io/badge/stars%20⭐-22-yellow)

BIN
title_image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB