Spaces:
Running
Running
def parse_input(file): | |
robots = [] | |
with open(file, 'r') as f: | |
for line in f: | |
parts = line.strip().split() | |
p_str = parts[0][2:-1].split(',') | |
v_str = parts[1][2:-1].split(',') | |
robots.append( | |
((int(p_str[0]), int(p_str[1])), (int(v_str[0]), int(v_str[1]))) | |
) | |
return robots | |
def simulate(robots, seconds, width, height): | |
positions = [] | |
for (px, py), (vx, vy) in robots: | |
new_x = (px + vx * seconds) % width | |
new_y = (py + vy * seconds) % height | |
positions.append((new_x, new_y)) | |
return positions | |
def calculate_safety_factor(positions, width, height): | |
quadrants = [0] * 4 | |
for x, y in positions: | |
if x < width // 2 and y < height // 2: | |
quadrants[0] += 1 | |
elif x > width // 2 and y < height // 2: | |
quadrants[1] += 1 | |
elif x < width // 2 and y > height // 2: | |
quadrants[2] += 1 | |
elif x > width // 2 and y > height // 2: | |
quadrants[3] += 1 | |
return quadrants[0] * quadrants[1] * quadrants[2] * quadrants[3] | |
def find_easter_egg(robots, width, height): | |
seconds = 0 | |
while True: | |
positions = simulate(robots, seconds, width, height) | |
min_x = min(p[0] for p in positions) | |
max_x = max(p[0] for p in positions) | |
min_y = min(p[1] for p in positions) | |
max_y = max(p[1] for p in positions) | |
if (max_x - min_x) * (max_y - min_y) < 1000: # Adjust threshold as needed | |
return seconds | |
seconds += 1 | |
file = "./input.txt" | |
robots = parse_input(file) | |
width = 101 | |
height = 103 | |
positions_after_100 = simulate(robots, 100, width, height) | |
safety_factor = calculate_safety_factor(positions_after_100, width, height) | |
print(safety_factor) | |
easter_egg_time = find_easter_egg(robots, width, height) | |
print(easter_egg_time) |