2.py (1560B) [raw]
1 #!/usr/bin/env python3 2 import sys 3 import re 4 5 buta_re = re.compile("Button A: X\+(\d+), Y\+(\d+)") 6 butb_re = re.compile("Button B: X\+(\d+), Y\+(\d+)") 7 priz_re = re.compile("Prize: X=(\d+), Y=(\d+)") 8 9 def parse(): 10 games = [] 11 game = {} 12 for l in sys.stdin: 13 am = buta_re.match(l) 14 bm = butb_re.match(l) 15 pm = priz_re.match(l) 16 if am: 17 game["A"] = [int(x) for x in am.groups(1)] 18 elif bm: 19 game["B"] = [int(x) for x in bm.groups(1)] 20 elif pm: 21 game["P"] = [int(x) + 10000000000000 for x in pm.groups(1)] 22 else: 23 games.append(game) 24 game = {} 25 if game: 26 games.append(game) 27 return games 28 29 # Its a linear equation, so they should interesect exactly 30 # once, not at all, or continuously (same line). 31 # 32 # For pt 2, we can't brute force--have to solve it! 33 # 34 # 94a + 22b = 8400 35 # 34a + 67b = 5400 36 # 37 # P1 = A1a + B1b -> a = (P1 - B1b)/A1 = P1A2 - B1A2b 38 # P2 = A2a + B2b -> a = (P2 - B2b)/A2 = P2A1 - B2A1b 39 # 40 # P1A2 - B1A2b = P2A1 - B2A1b 41 # P1A2 - P2A1 = B1A2b - B2A1b 42 # b = (P1A2 - P2A1) / (B1A2 - B2A1) 43 def solve(game): 44 P1, P2 = game['P'] 45 A1, A2 = game['A'] 46 B1, B2 = game['B'] 47 b = (P1 * A2 - P2 * A1) / (B1 * A2 - B2 * A1) 48 a = (P1 - B1 * b) / A1 49 if b != int(b) or b < 0 or a != int(a) or a < 0: 50 return None 51 return (a, b) 52 53 54 if __name__ == '__main__': 55 tot = 0 56 games = parse() 57 for g in games: 58 sol = solve(g) 59 if sol is not None: 60 tot += sol[0] * 3 + sol[1] 61 print(tot)