#!/usr/bin/env python3 import sys import re buta_re = re.compile("Button A: X\+(\d+), Y\+(\d+)") butb_re = re.compile("Button B: X\+(\d+), Y\+(\d+)") priz_re = re.compile("Prize: X=(\d+), Y=(\d+)") def parse(): games = [] game = {} for l in sys.stdin: am = buta_re.match(l) bm = butb_re.match(l) pm = priz_re.match(l) if am: game["A"] = [int(x) for x in am.groups(1)] elif bm: game["B"] = [int(x) for x in bm.groups(1)] elif pm: game["P"] = [int(x) for x in pm.groups(1)] else: games.append(game) game = {} if game: games.append(game) return games # Its a linear equation, so they should interesect exactly # once, not at all, or continuously (same line). # Searching the entire b space first (inner loop) gives # us the cheapest if they're the same line # # For pt 1, we just brute force it rather than solve it def solve(game): for a in range(101): for b in range(101): if a * game['A'][0] + b * game['B'][0] == game['P'][0]: if a * game['A'][1] + b * game['B'][1] == game['P'][1]: return (a, b) return None if __name__ == '__main__': tot = 0 games = parse() for g in games: sol = solve(g) if sol is not None: tot += sol[0] * 3 + sol[1] print(tot)