aoc

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

1.py (1730B) [raw]


      1 #!/usr/bin/env python3
      2 import sys
      3 import re
      4 
      5 class Bot:
      6     def __init__(self, x, y, dx, dy):
      7         self.x = x
      8         self.y = y
      9         self.dx = dx
     10         self.dy = dy
     11     def __str__(self):
     12         return f"Bot({self.x}, {self.y}, {self.dx}, {self.dy})"
     13 
     14 lre = re.compile("p=(\d+),(\d+) v=(-?\d+),(-?\d+)")
     15 
     16 def viewmap(bots, maxxy, maxy):
     17     locs = {}
     18     for b in bots:
     19         locs[(b.x, b.y)] = locs.get((b.x, b.y), 0) + 1
     20 
     21     for y in range(maxy):
     22         for x in range(maxx):
     23             if (x, y) in locs:
     24                 print(locs[x, y], end="")
     25             else:
     26                 print(".", end="")
     27         print("")
     28 
     29 def cycle(bots, maxx, maxy):
     30     for b in bots:
     31         b.x = (b.x + b.dx) % maxx
     32         b.y = (b.y + b.dy) % maxy
     33 
     34 def score(bots, maxx, maxy):
     35     quads = [0, 0, 0, 0]  # top-left, top-right, bot-left, bot-right
     36     for b in bots:
     37         if b.x == maxx // 2 or b.y == maxy // 2:
     38             continue
     39         else:
     40             quad = 0
     41             if b.x > maxx // 2:
     42                 quad += 1
     43             if b.y > maxy // 2:
     44                 quad += 2
     45             quads[quad] += 1
     46     return quads[0] * quads[1] * quads[2] * quads[3]
     47 
     48 def parse():
     49     bots = []
     50     maxx = 0
     51     maxy = 0
     52     for l in sys.stdin:
     53         m = lre.match(l)
     54         nums = [int(x) for x in m.groups()]
     55         b = Bot(*nums)
     56         bots.append(b)
     57         if b.x > maxx:
     58             maxx = b.x
     59         if b.y > maxy:
     60             maxy = b.y
     61     return bots, maxx + 1, maxy + 1
     62 
     63 if __name__ == '__main__':
     64     bots, maxx, maxy = parse()
     65     # viewmap(bots, maxx, maxy)
     66     for i in range(100):
     67         cycle(bots, maxx, maxy)
     68     # print("---")
     69     # viewmap(bots, maxx, maxy)
     70 
     71     print(score(bots, maxx, maxy))