lint and analysis

This commit is contained in:
2023-12-15 22:46:01 +01:00
parent 55799cbd22
commit b3b1e40b4e
12 changed files with 441 additions and 181 deletions

View File

@@ -1,13 +1,14 @@
def read_grid(file_path):
"""Reads the grid from a file and returns it as a 2D list."""
try:
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
grid = [list(line.strip()) for line in file]
return grid
except Exception as e:
print(f"Error reading file {file_path}: {e}")
raise
def move_rocks_north(grid):
"""Moves all rounded rocks 'O' north as far as possible."""
rows = len(grid)
@@ -15,12 +16,16 @@ def move_rocks_north(grid):
for col in range(cols):
for row in range(1, rows): # Start from second row
if grid[row][col] == 'O':
if grid[row][col] == "O":
target_row = row
while target_row > 0 and grid[target_row-1][col] == '.':
while target_row > 0 and grid[target_row - 1][col] == ".":
target_row -= 1
if target_row != row:
grid[target_row][col], grid[row][col] = grid[row][col], grid[target_row][col]
grid[target_row][col], grid[row][col] = (
grid[row][col],
grid[target_row][col],
)
def calculate_load(grid):
"""Calculates the total load on the north support beams."""
@@ -29,24 +34,25 @@ def calculate_load(grid):
for row in range(rows):
for cell in grid[row]:
if cell == 'O':
total_load += (rows - row)
if cell == "O":
total_load += rows - row
return total_load
def run_simulation(file_path):
"""Runs the rock-moving simulation and returns the total load."""
try:
grid = read_grid(file_path)
print(f"Initial Grid from {file_path}:")
for row in grid:
print(''.join(row))
print("".join(row))
move_rocks_north(grid)
print(f"Grid after moving rocks north from {file_path}:")
for row in grid:
print(''.join(row))
print("".join(row))
total_load = calculate_load(grid)
return total_load
@@ -54,6 +60,7 @@ def run_simulation(file_path):
print(f"Error during simulation for file {file_path}: {e}")
raise
def test_simulation():
"""Runs test simulation and asserts the expected output."""
test_file = "../test.txt"
@@ -63,9 +70,12 @@ def test_simulation():
actual_load = run_simulation(test_file)
print(f"Test simulation load: {actual_load}")
assert actual_load == expected_load, f"Test failed: expected {expected_load}, got {actual_load}"
assert (
actual_load == expected_load
), f"Test failed: expected {expected_load}, got {actual_load}"
print("Test passed successfully.")
def main():
"""Main function to run the test and then the actual simulation."""
try:
@@ -78,6 +88,7 @@ def main():
except Exception as e:
print(f"Error in main function: {e}")
# Run the main function
if __name__ == "__main__":
main()

View File

@@ -1,13 +1,14 @@
def read_grid(file_path):
"""Reads the grid from a file and returns it as a 2D list."""
try:
with open(file_path, 'r') as file:
with open(file_path, "r") as file:
grid = [list(line.strip()) for line in file]
return grid
except Exception as e:
print(f"Error reading file {file_path}: {e}")
raise
def tilt_grid(grid, direction):
"""Tilts the grid in the specified direction and moves the rounded rocks."""
rows, cols = len(grid), len(grid[0])
@@ -16,45 +17,57 @@ def tilt_grid(grid, direction):
if direction == "north":
for col in range(cols):
for row in range(1, rows):
if grid[row][col] == 'O':
if grid[row][col] == "O":
target_row = row
while target_row > 0 and grid[target_row-1][col] == '.':
while target_row > 0 and grid[target_row - 1][col] == ".":
target_row -= 1
if target_row != row:
grid[target_row][col], grid[row][col] = grid[row][col], grid[target_row][col]
grid[target_row][col], grid[row][col] = (
grid[row][col],
grid[target_row][col],
)
# West: Move rocks to the left
elif direction == "west":
for row in range(rows):
for col in range(1, cols):
if grid[row][col] == 'O':
if grid[row][col] == "O":
target_col = col
while target_col > 0 and grid[row][target_col-1] == '.':
while target_col > 0 and grid[row][target_col - 1] == ".":
target_col -= 1
if target_col != col:
grid[row][target_col], grid[row][col] = grid[row][col], grid[row][target_col]
grid[row][target_col], grid[row][col] = (
grid[row][col],
grid[row][target_col],
)
# South: Move rocks downwards
elif direction == "south":
for col in range(cols):
for row in range(rows - 2, -1, -1): # Start from the second last row
if grid[row][col] == 'O':
if grid[row][col] == "O":
target_row = row
while target_row < rows - 1 and grid[target_row + 1][col] == '.':
while target_row < rows - 1 and grid[target_row + 1][col] == ".":
target_row += 1
if target_row != row:
grid[target_row][col], grid[row][col] = grid[row][col], grid[target_row][col]
grid[target_row][col], grid[row][col] = (
grid[row][col],
grid[target_row][col],
)
# East: Move rocks to the right
elif direction == "east":
for row in range(rows):
for col in range(cols - 2, -1, -1): # Start from the second last column
if grid[row][col] == 'O':
if grid[row][col] == "O":
target_col = col
while target_col < cols - 1 and grid[row][target_col + 1] == '.':
while target_col < cols - 1 and grid[row][target_col + 1] == ".":
target_col += 1
if target_col != col:
grid[row][target_col], grid[row][col] = grid[row][col], grid[row][target_col]
grid[row][target_col], grid[row][col] = (
grid[row][col],
grid[row][target_col],
)
def run_spin_cycles(grid, cycles):
@@ -64,20 +77,23 @@ def run_spin_cycles(grid, cycles):
tilt_grid(grid, direction)
# Implement pattern detection or optimization here if needed
def run_simulation_with_cycles(file_path, cycles):
"""Runs the simulation with spin cycles and returns the total load."""
try:
grid = read_grid(file_path)
run_spin_cycles(grid, cycles)
actual_cycles = run_spin_cycles_with_optimization(grid, cycles)
total_load = calculate_load(grid)
return total_load
except Exception as e:
print(f"Error during simulation for file {file_path}: {e}")
raise
def grid_to_string(grid):
"""Converts the grid to a string for easy comparison."""
return '\n'.join(''.join(row) for row in grid)
return "\n".join("".join(row) for row in grid)
def run_spin_cycles_with_optimization(grid, max_cycles):
"""Runs spin cycles on the grid with optimizations for large cycle numbers."""
@@ -106,30 +122,28 @@ def test_simulation_with_cycles():
actual_load = run_simulation_with_cycles(test_file, 1000000000)
print(f"Test simulation load after cycles: {actual_load}")
assert actual_load == expected_load_after_cycles, f"Test failed: expected {expected_load_after_cycles}, got {actual_load}"
assert (
actual_load == expected_load_after_cycles
), f"Test failed: expected {expected_load_after_cycles}, got {actual_load}"
print("Test passed successfully.")
def main():
"""Main function to run the test and then the actual simulation with cycles."""
try:
test_simulation_with_cycles()
input_file = "../input.txt"
cycles = 1000000000
print("\nRunning actual simulation with cycles...")
grid = read_grid(input_file)
actual_cycles = run_spin_cycles_with_optimization(grid, cycles)
total_load = calculate_load(grid)
#total_load = run_simulation_with_cycles(input_file, cycles)
# total_load = run_simulation_with_cycles(input_file, cycles)
print(f"Total load from actual simulation with cycles: {total_load}")
except Exception as e:
print(f"Error in main function: {e}")
# Run the main function
if __name__ == "__main__":
main()
# Note: The actual implementation of tilt logic for 'west', 'south', and 'east' directions
# and any optimization techniques for handling a large number of cycles are not included here
# due to complexity and are left as an exercise. This code provides a framework for how
# the algorithm could be structured.