From 83ab3847e4fac224a4432015884f4764f1d9d985 Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Tue, 21 Mar 2023 01:45:18 +0100 Subject: [PATCH] Refactored day 12 with lib --- day12.py | 45 ++++++++++++--------------------------------- 1 file changed, 12 insertions(+), 33 deletions(-) diff --git a/day12.py b/day12.py index 57208ef..d011575 100644 --- a/day12.py +++ b/day12.py @@ -1,53 +1,29 @@ #!/usr/bin/env python3 -from itertools import combinations +from itertools import combinations, starmap from math import gcd from functools import reduce +from lib import vector + def lcm(a, b): return (a * b) // gcd(a, b) -def comp(a, b): - def f(arg): - x, y = arg - if x < y: - return 1 - elif x == y: - return 0 - return -1 - return Vector(map(f, zip(a, b))) - -def parse(line): - coords = (int(x[2:]) for x in line[1:-1].split(', ')) - return Moon(coords) - -class Vector(tuple): - - def __add__(self, other): - return Vector(map(sum, zip(self, other))) - - def __neg__(self): - return Vector((-x for x in self)) - - def __sub__(self, other): - return self + (- other) - - def __repr__(self): - return super(Vector, self).__repr__() +def cmp(x, y): + return (x < y) - (x > y) class Moon: def __init__(self, pos, vel=None): - self.pos = Vector(pos) + self.pos = vector(pos) if vel == None: - self.vel = Vector([0]*len(self.pos)) - else: - self.vel = Vector(vel) + vel = vector([0]*len(self.pos)) + self.vel = vector(vel) def restrict(self, i): return Moon((self.pos[i],), (self.vel[i],)) def apply_gravity(self, b): - self.vel += comp(self.pos, b.pos) + self.vel += starmap(cmp, zip(self.pos, b.pos)) def apply_velocity(self): self.pos += self.vel @@ -114,7 +90,10 @@ def find_period(sys): return step return reduce(lcm, (find_period(sys.restrict(i)) for i in range(sys.dimension()))) + + def preproc(puzzle_input): + parse = lambda line : Moon(int(x[2:]) for x in line[1:-1].split(', ')) return System(map(parse, puzzle_input.split('\n'))) def partI(moons):