1
0
Fork 0

add 2024/day14.1

This commit is contained in:
Sebastian Mark 2024-12-14 11:57:36 +01:00
parent f5c0c4d52f
commit 456512b9fd

87
2024/14/main.py Normal file
View file

@ -0,0 +1,87 @@
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Author: Sebastian Mark
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string,no-else-return
import re
def readinput():
with open("input", "r", encoding="utf-8") as file:
robots = []
for line in file:
regex = r"p=(.?\d+),(.?\d+) v=(.?\d+),(.?\d+)"
m = re.findall(regex, line)[0]
robots.append(
{
"pos": (int(m[0]), int(m[1])), # x,y
"move": (int(m[2]), int(m[3])), # x,y
}
)
return robots
def get_robot_pos_after_time(area: dict, robot: tuple, seconds: int) -> tuple:
for _ in range(seconds):
nxtx = (robot["pos"][0] + robot["move"][0]) % area["width"]
nxty = (robot["pos"][1] + robot["move"][1]) % area["height"]
robot["pos"] = nxtx, nxty
return robot["pos"]
def get_quadrant(area: dict, position: tuple) -> int:
middle_x = area["width"] // 2
middle_y = area["height"] // 2
if position[0] == middle_x or position[1] == middle_y:
return 0
if position[1] < middle_y:
if position[0] < middle_x:
return 1
else:
return 2
else:
if position[0] < middle_x:
return 3
else:
return 4
def assign_qadrants(area: dict, positions: dict) -> list:
quadrant_count = {}
for pos, count in positions.items():
quadrant = get_quadrant(area, pos)
if quadrant != 0:
quadrant_count[quadrant] = quadrant_count.get(quadrant, 0) + count
return quadrant_count
def main():
robots = readinput()
area = {"width": 101, "height": 103}
seconds = 100
# part 1
positions = {}
for robot in robots:
pos = get_robot_pos_after_time(area, robot, seconds)
positions[pos] = positions.get(pos, 0) + 1
safety_factor = 1
quadrant_count = assign_qadrants(area, positions)
for c in quadrant_count.values():
safety_factor *= c
print("Safety factor: %d" % safety_factor)
if __name__ == "__main__":
main()