Refactored day 12 with lib

master
Tibor Bizjak 2023-03-21 01:45:18 +01:00
parent 1d2a679eb8
commit 83ab3847e4
1 changed files with 12 additions and 33 deletions

View File

@ -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):