11.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. lines = []
  2. with open("11.input") as f:
  3. for line in f.readlines():
  4. lines.append(list(line.strip()))
  5. def pretty_print(map):
  6. print('=' * 20)
  7. for line in map:
  8. for c in line:
  9. print(c, end='')
  10. print("")
  11. def occupied_count(map, x_in, y_in, distance):
  12. dirs = [
  13. (-1, -1), (-1, 0), (-1, 1),
  14. (0, -1), (0, 1),
  15. (1, -1), (1, 0), (1, 1),
  16. ]
  17. count = 0
  18. for (y_dir, x_dir) in dirs:
  19. for i in range(1, distance + 1):
  20. y = y_in + y_dir * i
  21. x = x_in + x_dir * i
  22. if y < 0:
  23. break
  24. if x < 0:
  25. break
  26. if y > len(map) - 1:
  27. break
  28. if x > len(map[0]) - 1:
  29. break
  30. char = map[y][x]
  31. if char == '.':
  32. continue
  33. elif char == 'L':
  34. break
  35. elif char == '#':
  36. count += 1
  37. break
  38. return count
  39. def transform(map, distance, tolerance):
  40. next = list(map)
  41. for (y, line) in enumerate(map):
  42. next[y] = list(line)
  43. for (x, char) in enumerate(line):
  44. if char == '.':
  45. continue
  46. elif char == 'L':
  47. if occupied_count(map, x, y, distance) == 0:
  48. next[y][x] = '#'
  49. elif char == '#':
  50. if occupied_count(map, x, y, distance) >= tolerance:
  51. next[y][x] = 'L'
  52. return next
  53. def iterate(map, distance, tolerance):
  54. current = map
  55. while True:
  56. next = transform(current, distance, tolerance)
  57. #pretty_print(next)
  58. if next == current:
  59. break
  60. current = next
  61. return current
  62. print(len([c for l in iterate(lines, 1, 4) for c in l if c == '#']))
  63. print(len([c for l in iterate(lines, 1000, 5) for c in l if c == '#']))
  64. current = lines