18_digplan.py 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/env python3
  2. import sys
  3. from itertools import pairwise
  4. def parse(inp):
  5. DXDY = (1, 0), (0, 1), (-1, 0), (0, -1)
  6. for line in inp:
  7. direction, distance, color = line.split()
  8. normal_instruction = DXDY['RDLU'.index(direction)], int(distance)
  9. color_instruction = DXDY[int(color[7])], int(color[2:7], 16)
  10. yield normal_instruction, color_instruction
  11. def follow(instructions):
  12. x = y = 0
  13. for (dx, dy), distance in instructions:
  14. x += dx * distance
  15. y += dy * distance
  16. yield x, y
  17. def dig(instructions):
  18. x, y = zip(*follow(instructions))
  19. v = len(x)
  20. area = abs(sum(x[i] * y[(i + 1) % v] - y[i] * x[(i + 1) % v]
  21. for i in range(v))) // 2 # Shoelace formula
  22. outer = sum(abs(bx - ax + by - ay)
  23. for (ax, ay), (bx, by) in pairwise(zip(x + x[:1], y + y[:1])))
  24. inner = area - outer // 2 + 1 # Pick's theorem
  25. return outer + inner
  26. normal, color = zip(*parse(sys.stdin))
  27. print(dig(normal))
  28. print(dig(color))