diff --git a/2024/13/solution.py b/2024/13/solution.py index ddfa762..abec23f 100644 --- a/2024/13/solution.py +++ b/2024/13/solution.py @@ -1,6 +1,6 @@ #!/bin/python3 import sys,time,re -from sympy import * +from sympy import symbols,solve,Eq from pprint import pprint sys.path.insert(0, '../../') from fred import list2int,get_re,nprint,lprint,loadFile @@ -8,48 +8,39 @@ 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(): - 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)])) - + 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 - 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],inst[1]) - 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() -#rint('Part 1:',part1(), '\t\t', round((time.time() - start_time)*1000), 'ms') +print('Part 1:',part1(), '\t\t', round((time.time() - start_time)*1000), 'ms') ######################################### @@ -90,10 +81,7 @@ def part2(): if s: result += s[x]*a_cost result += s[y]*b_cost - #input() return result - -start_time = time.time() - + start_time = time.time() print('Part 2:',part2(), '\t\t', round((time.time() - start_time)*1000), 'ms') \ No newline at end of file diff --git a/solution.py b/solution.py index 474f534..a8f60c2 100644 --- a/solution.py +++ b/solution.py @@ -24,8 +24,8 @@ print('Part 1:',part1(), '\t\t', round((time.time() - start_time)*1000), 'ms') # Part 2 # # # ######################################### -def part1(): +def part2(): return start_time = time.time() -print('Part 2:',part1(), '\t\t', round((time.time() - start_time)*1000), 'ms') \ No newline at end of file +print('Part 2:',part2(), '\t\t', round((time.time() - start_time)*1000), 'ms') \ No newline at end of file