aoc

Advent of Code Solutions
git clone git://git.alexkarle.com.com/aoc
Log | Files | Refs | README | LICENSE

1.py (1407B) [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) 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 # Searching the entire b space first (inner loop) gives
     32 # us the cheapest if they're the same line
     33 #
     34 # For pt 1, we just brute force it rather than solve it
     35 def solve(game):
     36     for a in range(101):
     37         for b in range(101):
     38             if a * game['A'][0] + b * game['B'][0] == game['P'][0]:
     39                 if a * game['A'][1] + b * game['B'][1] == game['P'][1]:
     40                     return (a, b)
     41     return None
     42 
     43 
     44 if __name__ == '__main__':
     45     tot = 0
     46     games = parse()
     47     for g in games:
     48         sol = solve(g)
     49         if sol is not None:
     50             tot += sol[0] * 3 + sol[1]
     51     print(tot)