Spaces:
Running
Running
def parse_input(file_path): | |
robots = [] | |
with open(file_path, 'r') as f: | |
for line in f: | |
p, v = line.strip().split() | |
px, py = map(int, p[2:].split(',')) | |
vx, vy = map(int, v[2:].split(',')) | |
robots.append((px, py, vx, vy)) | |
return robots | |
def update_position(x, y, vx, vy, width, height): | |
x = (x + vx) % width | |
y = (y + vy) % height | |
return x, y | |
def count_robots_in_quadrants(positions, width, height): | |
mid_x = width // 2 | |
mid_y = height // 2 | |
quadrants = [0] * 4 # TL, TR, BL, BR | |
for x, y in positions: | |
if x == mid_x or y == mid_y: | |
continue | |
if x < mid_x: | |
if y < mid_y: | |
quadrants[0] += 1 # Top-left | |
else: | |
quadrants[2] += 1 # Bottom-left | |
else: | |
if y < mid_y: | |
quadrants[1] += 1 # Top-right | |
else: | |
quadrants[3] += 1 # Bottom-right | |
return quadrants | |
def is_christmas_tree(positions, width, height): | |
# Create a grid representation | |
grid = [[0] * width for _ in range(height)] | |
for x, y in positions: | |
grid[y][x] += 1 | |
# Check for basic Christmas tree pattern | |
# This is a simplified check - adjust pattern as needed | |
tree_pattern = False | |
center_x = width // 2 | |
# Check for triangular shape with a trunk | |
tree_points = 0 | |
trunk_points = 0 | |
for y in range(height): | |
row_count = sum(1 for x in range(width) if grid[y][x] > 0) | |
if row_count > 0: | |
if row_count == 1 and grid[y][center_x] > 0: | |
trunk_points += 1 | |
elif row_count > 1: | |
tree_points += 1 | |
return tree_points >= 5 and trunk_points >= 2 | |
def solve_part1(robots, width=101, height=103): | |
positions = set() | |
for px, py, vx, vy in robots: | |
x, y = px, py | |
for _ in range(100): | |
x, y = update_position(x, y, vx, vy, width, height) | |
positions.add((x, y)) | |
quadrants = count_robots_in_quadrants(positions, width, height) | |
return str(quadrants[0] * quadrants[1] * quadrants[2] * quadrants[3]) | |
def solve_part2(robots, width=101, height=103, max_seconds=10000): | |
for second in range(max_seconds): | |
positions = set() | |
for px, py, vx, vy in robots: | |
x, y = px, py | |
for _ in range(second): | |
x, y = update_position(x, y, vx, vy, width, height) | |
positions.add((x, y)) | |
if is_christmas_tree(positions, width, height): | |
return str(second) | |
return "Pattern not found" | |
# Read and solve | |
robots = parse_input("./input.txt") | |
# Part 1 | |
print(solve_part1(robots)) | |
# Part 2 | |
print(solve_part2(robots)) |