24.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. input = []
  2. with open("24.input") as f:
  3. for line in f.readlines():
  4. seq = []
  5. i = iter(list(line.strip()))
  6. c1 = next(i, None)
  7. while c1 != None:
  8. if c1 in ['s', 'n']:
  9. seq.append(c1 + next(i))
  10. else:
  11. seq.append(c1)
  12. c1 = next(i, None)
  13. input.append(seq)
  14. def get_pos(seq):
  15. pos = [0, 0]
  16. for move in seq:
  17. if move == 'w':
  18. pos[0] -= 2
  19. elif move == 'e':
  20. pos[0] += 2
  21. else:
  22. if move[0] == 's':
  23. pos[1] += 1
  24. else:
  25. pos[1] -= 1
  26. if move[1] == 'w':
  27. pos[0] -= 1
  28. else:
  29. pos[0] += 1
  30. return tuple(pos)
  31. counts = {}
  32. for seq in input:
  33. pos = get_pos(seq)
  34. if pos not in counts:
  35. counts[pos] = 0
  36. counts[pos] += 1
  37. print("Answer 1:", len([v for v in counts.values() if v % 2 == 1]))
  38. def count_adjacent(map, pos):
  39. x, y = pos
  40. adjacent = [(-2, 0), (2, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
  41. return len([1 for (off_x, off_y) in adjacent if map.get((x + off_x, y + off_y), False)])
  42. map = {k: v % 2 == 1 for (k, v) in counts.items()}
  43. max_x = max([abs(x) for (x, y) in map.keys()]) + 1
  44. max_y = max([abs(y) for (x, y) in map.keys()]) + 1
  45. for i in range(0, 100):
  46. next_map = {}
  47. for x in range(-max_x, max_x + 1):
  48. for y in range(-max_y, max_y + 1):
  49. if (x + y) % 2 == 1:
  50. continue
  51. count = count_adjacent(map, (x, y))
  52. if map.get((x, y), False) == True:
  53. next_map[(x, y)] = count in [1, 2]
  54. else:
  55. next_map[(x, y)] = count == 2
  56. map = next_map
  57. max_y += 1
  58. max_x += 2
  59. #print("Day {}: {}".format(i + 1, sum([1 for v in map.values() if v])))
  60. print("Answer 2:", sum([1 for v in map.values() if v]))