#!/bin/python3 import sys,time,re from sympy import symbols,solve,Eq from pprint import pprint sys.path.insert(0, '../../') from fred import list2int,get_re,nprint,lprint,loadFile start_time = time.time() input_f = 'input' # Both Part 1 and Part was solved the same way, but # after solving them, i tried to optimize the loader # on Part 1. # I left Part 2 as-is, to show how it was done first. ######################################### # # # Part 1 # # # ######################################### def part1(): result = 0 x,y = symbols('x y',integer=True) a_cost = 3 b_cost = 1 with open(input_f) as file: while (lines := list(file.readline() for _ in range(4))): match = re.findall(r"X[\+|=](\d+), Y[\+|=](\d+)","".join(lines).strip()) match = [(int(x), int(y)) for x, y in match] if match: eq1 = Eq(match[0][0]*x + match[1][0]*y,match[2][0]) eq2 = Eq(match[0][1]*x + match[1][1]*y,match[2][1]) s = solve((eq1,eq2),(x,y)) if s: result += s[x]*a_cost result += s[y]*b_cost else: break return result start_time = time.time() print('Part 1:',part1(), '\t\t', round((time.time() - start_time)*1000), 'ms') ######################################### # # # Part 2 # # # ######################################### def part2(): instructions = [] with open(input_f) as file: for line in file: match = get_re(r".*X[\+|=](\d+), Y[\+|=](\d+)",line.rstrip()) if match: instructions.append(list2int([match.group(1),match.group(2)])) a_cost = 3 b_cost = 1 a = () b = () r = () x,y = symbols('x y',integer=True) result = 0 for idx, inst in enumerate(instructions): if idx%3 == 0: a = (inst[0],inst[1]) elif idx%3 == 1: b = (inst[0],inst[1]) elif idx%3 == 2: r = (inst[0]+10000000000000,inst[1]+10000000000000) eq1 = Eq(a[0]*x + b[0]*y,r[0]) eq2 = Eq(a[1]*x + b[1]*y,r[1]) s = solve((eq1,eq2),(x,y)) if s: result += s[x]*a_cost result += s[y]*b_cost return result start_time = time.time() print('Part 2:',part2(), '\t\t', round((time.time() - start_time)*1000), 'ms')