Solutions to Advent of Code 2017 https://adventofcode.com/2017/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

21.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import numpy as np
  2. with open('data/21.txt') as file:
  3. mappings = dict()
  4. for line in file.readlines():
  5. parts = tuple(map(lambda p: np.array(list(map(lambda r: [c == '#' for c in r], p.split('/')))),
  6. line.strip().split(' => ')))
  7. # All possible transformations of our mappings:
  8. # - 0, 90, 180 and 270 degree rotations
  9. # - vertical (up<>down) flip followed by the 4 rotations
  10. # - horizontal (left<>right) flip followed by the 4 rotations
  11. # ...Some of these may be equivalent...
  12. keys = [
  13. *(np.rot90(parts[0], k) for k in range(3)),
  14. *(np.rot90(np.flipud(parts[0]), k) for k in range(3)),
  15. *(np.rot90(np.fliplr(parts[0]), k) for k in range(3)),
  16. ]
  17. for key in keys:
  18. mappings[key.tobytes()] = parts[1]
  19. def expand(old_grid, length, oss, nss):
  20. """
  21. Expands a grid by replacing all segments with their mapped versions.
  22. :param old_grid: The grid to expand
  23. :param length: The current size of the grid (length in any direction)
  24. :param oss: The size of the segment to be replaced (old segment size)
  25. :param nss: The size of the segment that will replace it (new segment size)
  26. :return: A new grid, with each segment expanded
  27. """
  28. new_grid = np.empty((length // oss * nss, length // oss * nss), dtype=bool)
  29. for x in range(0, length, oss):
  30. for y in range(0, length, oss):
  31. new_x = x // oss * nss
  32. new_y = y // oss * nss
  33. new_grid[new_x:new_x+nss, new_y:new_y+nss] = mappings[old_grid[x:x + oss, y:y + oss].tobytes()]
  34. return new_grid
  35. grid = np.array([[False, True, False], [False, False, True], [True, True, True]])
  36. for i in range(18):
  37. size = len(grid)
  38. grid = expand(grid, size, 2, 3) if size % 2 == 0 else expand(grid, size, 3, 4)
  39. if i == 4:
  40. print(f'Part one: {sum(sum(grid))}')
  41. elif i == 17:
  42. print(f'Part two: {sum(sum(grid))}')