Guest User

day9part2

a guest
Dec 9th, 2025
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | Source Code | 0 0
  1. points = []
  2. with open("day9_input.txt") as f:
  3.     line = f.readline()
  4.     while line:
  5.         points.append(tuple([int(n) for n in line.split(',')]))
  6.         line = f.readline()
  7. num_points = len(points)
  8.        
  9. def area(c1, c2):
  10.     x1, y1 = c1
  11.     x2, y2 = c2
  12.     return (abs(x1-x2)+1)*(abs(y1-y2)+1)
  13.    
  14.  
  15. horizontal_edges = []
  16. vertical_edges = []
  17. pointcloud = []
  18. for i in range(num_points):
  19.     while len(pointcloud) <= points[i][1]:
  20.         pointcloud.append([])
  21.     pointcloud[points[i][1]].append(points[i][0])
  22.     j = (i+1)%num_points
  23.  
  24.    
  25.     if points[i][0] == points[j][0]:
  26.         while len(vertical_edges) <= points[i][0]:
  27.             vertical_edges.append([])
  28.         vertical_edges[points[i][0]].append((min(points[i][1], points[j][1]), max(points[i][1], points[j][1])))
  29.     else:
  30.         while len(horizontal_edges) <= points[i][1]:
  31.             horizontal_edges.append([])
  32.         horizontal_edges[points[i][1]].append((min(points[i][0], points[j][0]), max(points[i][0], points[j][0])))
  33.        
  34. for i in range(len(vertical_edges)):
  35.     vertical_edges[i].sort()
  36.  
  37. for i in range(len(horizontal_edges)):
  38.     horizontal_edges[i].sort()
  39.    
  40. squares = []
  41. for i, c1 in enumerate(points):
  42.     for c2 in points[i+1:]:
  43.         squares.append((c1, c2, area(c1,c2)))
  44.  
  45. squares.sort(key=lambda n : n[2], reverse=True)
  46.  
  47.    
  48. candidates = []
  49. for c1, c2, d in squares:
  50.     x1, y1 = c1
  51.     x2, y2 = c2
  52.     top = min(y1,y2)
  53.     bottom = max(y1,y2)
  54.     left = min(x1, x2)
  55.     right = max(x1, x2)
  56.     #let's first try to get any squares without any inner points
  57.     failed = False
  58.     for y in range(top+1, bottom):
  59.         for x in pointcloud[y]:
  60.             if x > left and x < right:
  61.                 failed = True
  62.                 break
  63.         for l,r in horizontal_edges[y]:
  64.             if left > l and left < r:
  65.                 failed = True
  66.                 break
  67.         if failed:
  68.             break
  69.     if failed:
  70.         continue
  71.  
  72.     candidates.append(d)
  73.     print(c1, c2, d)
  74.     break
  75.    
  76. print(candidates)
  77.    
Advertisement
Add Comment
Please, Sign In to add comment