17.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. grid_3d = {}
  2. grid_4d = {}
  3. with open("17.input") as f:
  4. for (y, line) in enumerate(f.readlines()):
  5. for (x, c) in enumerate(list(line.strip())):
  6. grid_3d[(x, y, 0)] = c
  7. grid_4d[(x, y, 0, 0)] = c
  8. def get_surrounding(grid, locked_coords, free_coords):
  9. if len(free_coords) == 0:
  10. if grid.get(locked_coords, ".") == "#":
  11. return 1
  12. else:
  13. return 0
  14. count = 0
  15. for x in range(free_coords[0] - 1, free_coords[0] + 2):
  16. count += get_surrounding(grid, tuple(list(locked_coords) + [x]), free_coords[1:])
  17. # Remove self
  18. if len(locked_coords) == 0 and grid.get(free_coords, '.') == '#':
  19. count -= 1
  20. return count
  21. def calc_new(grid, coords):
  22. count = get_surrounding(grid, (), coords)
  23. if grid.get(coords, '.') == '#':
  24. if count in [2, 3]:
  25. return '#'
  26. else:
  27. return '.'
  28. else:
  29. if count == 3:
  30. return '#'
  31. else:
  32. return '.'
  33. def cycle(grid, fixed_coords, sizes):
  34. new_grid = {}
  35. if sizes == []:
  36. new_grid[tuple(fixed_coords)] = calc_new(grid, tuple(fixed_coords))
  37. else:
  38. for x in sizes[0]:
  39. new_grid.update(cycle(grid, fixed_coords + [x], sizes[1:]))
  40. return new_grid
  41. def cycle_multiple(grid, start_sizes):
  42. my_grid = dict(grid)
  43. for i in range(1, 7):
  44. sizes = [range(-i, s + i) for s in start_sizes]
  45. my_grid = cycle(my_grid, [], sizes)
  46. return my_grid
  47. print("Answer 1:", len([1 for c in cycle_multiple(grid_3d, (8, 8, 1)).values() if c == '#']))
  48. print("Answer 2:", len([1 for c in cycle_multiple(grid_4d, (8, 8, 1, 1)).values() if c == '#']))