From d6d0f1a94f129d36151eac385076e5444893fb2b Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 12 Dec 2019 10:53:38 +0100 Subject: [PATCH] 2019: d12: ex1: add solution --- 2019/d12/ex1/ex1.py | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100755 2019/d12/ex1/ex1.py diff --git a/2019/d12/ex1/ex1.py b/2019/d12/ex1/ex1.py new file mode 100755 index 0000000..b3a708a --- /dev/null +++ b/2019/d12/ex1/ex1.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python + + +import re +import sys +from dataclasses import dataclass + + +@dataclass +class Position: + x: int + y: int + z: int + + +def line_to_pos(l: str) -> Position: + "" + regex = r"[^,]*), y=(?P[^,]*), z=(?P[^,]*)>" + match = re.search(regex, l) + assert match is not None # Sanity check + return Position(*(int(match.group(g)) for g in ("x", "y", "z"))) + + +def main() -> None: + asteroids = [line_to_pos(line) for line in sys.stdin.readlines()] + velocities = [Position(0, 0, 0) for __ in asteroids] + + for __ in range(1000): + for orig, v in zip(asteroids, velocities): + for other in asteroids: + if orig.x != other.x: + v.x += 1 if orig.x < other.x else -1 + if orig.y != other.y: + v.y += 1 if orig.y < other.y else -1 + if orig.z != other.z: + v.z += 1 if orig.z < other.z else -1 + + for asteroid, v in zip(asteroids, velocities): + asteroid.x += v.x + asteroid.y += v.y + asteroid.z += v.z + + pot = (abs(p.x) + abs(p.y) + abs(p.z) for p in asteroids) + kin = (abs(v.x) + abs(v.y) + abs(v.z) for v in velocities) + + print(sum(p * k for p, k in zip(pot, kin))) + + +if __name__ == "__main__": + main()