Advertisement
Guest User

Untitled

a guest
Dec 11th, 2020
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. from collections import deque
  2.  
  3. def part1(matrix,getNextState):
  4. res = 0
  5. n = len(matrix)
  6. m = len(matrix[0])
  7. q = deque()
  8.  
  9. for i in range(n):
  10. for j in range(m):
  11. if matrix[i][j] == "L":
  12. q.append([i,j,"L"])
  13.  
  14. leftForCurrRound = len(q)
  15. toUpdate = []
  16.  
  17. while q:
  18. i,j,_ = q.popleft()
  19. leftForCurrRound -= 1
  20. nextState = getNextState(i,j,matrix)
  21.  
  22. if nextState != matrix[i][j]:
  23. future = [i,j,nextState]
  24. q.append(future)
  25. toUpdate.append(future)
  26.  
  27. if not leftForCurrRound:
  28. leftForCurrRound = len(q)
  29. for nextI,nextJ,nextState in toUpdate:
  30. matrix[nextI][nextJ] = nextState
  31.  
  32. toUpdate = []
  33.  
  34. for i in range(n):
  35. for j in range(m):
  36. res += matrix[i][j] == "#"
  37.  
  38. return res
  39.  
  40. def getNextStatePart1(i,j,matrix):
  41. numOccupied = 0
  42.  
  43. for dy,dx in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:
  44. nextI = i + dy
  45. nextJ = j + dx
  46.  
  47. if not isValid(nextI,nextJ,matrix):
  48. continue
  49.  
  50. numOccupied += matrix[nextI][nextJ] == "#"
  51.  
  52. if matrix[i][j] == "L" and not numOccupied:
  53. return '#'
  54.  
  55. if matrix[i][j] == "#" and numOccupied >= 4:
  56. return 'L'
  57.  
  58. return matrix[i][j]
  59.  
  60. def getNextStatePart2(i,j,matrix):
  61. numOccupied = 0
  62.  
  63. for dy,dx in [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]:
  64. nextI = i + dy
  65. nextJ = j + dx
  66.  
  67. if not isValid(nextI,nextJ,matrix):
  68. continue
  69.  
  70. while isValid(nextI,nextJ,matrix) and matrix[nextI][nextJ] == ".":
  71. nextI += dy
  72. nextJ += dx
  73.  
  74. if isValid(nextI,nextJ,matrix):
  75. numOccupied += matrix[nextI][nextJ] == '#'
  76.  
  77. if matrix[i][j] == "L" and not numOccupied:
  78. return '#'
  79.  
  80. if matrix[i][j] == "#" and numOccupied >= 5:
  81. return 'L'
  82.  
  83. return matrix[i][j]
  84.  
  85. def isValid(i,j,matrix):
  86. return i >= 0 and i < len(matrix) and j >= 0 and j < len(matrix[0])
  87.  
  88. with open('input-01.txt') as f:
  89. matrix = []
  90.  
  91. for l in f.readlines():
  92. matrix.append([c for c in l.strip()])
  93.  
  94. print(part1([row[:] for row in matrix],getNextStatePart1),part1([row[:] for row in matrix],getNextStatePart2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement