Guest User

Untitled

a guest
Dec 10th, 2022
531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import numpy as np
  3.  
  4. def solve(data):
  5. ans1 = 0
  6. ans2 = 0
  7.  
  8. # Part 1
  9. # Determine high points surrounded by only lows in cardinal directions
  10. for (row, y) in zip(data, range(len(data))):
  11. data[y] = list(map(int, [*row]))
  12.  
  13. data = np.array(data)
  14. for (x, x_num) in zip(data, range(len(data))):
  15. for (y, y_num) in zip(x, range(len(x))):
  16. if (
  17. all(data[:x_num, y_num] < y) or # North
  18. all(data[x_num, y_num + 1:] < y) or # East
  19. all(data[x_num + 1:, y_num] < y) or # South
  20. all(data[x_num, :y_num] < y) # West
  21. ):
  22. ans1 += 1
  23.  
  24. # Part 2
  25. # Find tree with highest scenic score (product of visible trees in each direction)\
  26. scores = []
  27. for (x, x_num) in zip(data, range(len(data))):
  28. for (y, y_num) in zip(x, range(len(x))):
  29. score = 0
  30. tree_score = 1
  31. for tree in reversed(data[:x_num, y_num]): # North
  32. if y > tree:
  33. score += 1
  34. elif y <= tree: # When a tree blocks view
  35. score += 1
  36. break
  37. else: # When at the edge
  38. break
  39. tree_score *= score
  40.  
  41. score = 0
  42. for tree in data[x_num, y_num + 1:]: # East
  43. if y > tree:
  44. score += 1
  45. elif y <= tree:
  46. score += 1
  47. break
  48. else:
  49. break
  50. tree_score *= score
  51.  
  52. score = 0
  53. for tree in data[x_num + 1:, y_num]: # South
  54. if y > tree:
  55. score += 1
  56. elif y <= tree:
  57. score += 1
  58. break
  59. else:
  60. break
  61. tree_score *= score
  62.  
  63. score = 0
  64. for tree in reversed(data[x_num, :y_num]): # West
  65. if y > tree:
  66. score += 1
  67. elif y <= tree:
  68. score += 1
  69. break
  70. else:
  71. break
  72. tree_score *= score
  73. scores.append(tree_score)
  74.  
  75. ans2 = max(scores)
  76.  
  77. return ans1, ans2
  78.  
  79. if __name__ == '__main__':
  80. testing = False
  81.  
  82. # Reads lines into a list input
  83. print('Counting data...')
  84. file = 'testinput.txt' if testing else 'input.txt'
  85. with open(file) as f:
  86. data = f.read().splitlines()
  87.  
  88. ans = solve(data)
  89. print(f"Part 1 Solution: {ans[0]}")
  90. print(f"Part 2 Solution: {ans[1]}")
Advertisement
Add Comment
Please, Sign In to add comment