Skip to content

Commit 3dd86d8

Browse files
committed
feat: line-sweep-closest-points challenge
1 parent 2dbc9e5 commit 3dd86d8

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import List, Tuple
2+
import math
3+
import bisect
4+
5+
class ClosestPoints:
6+
def __init__(self, points: List[Tuple[int, int]]):
7+
self.points = sorted(points, key=lambda x: x[0])
8+
9+
def distance(self, p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
10+
return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
11+
12+
def find_closest_pair(self) -> Tuple[Tuple[int, int], Tuple[int, int], float]:
13+
active = []
14+
best_pair = (None, None)
15+
best_dist = float('inf')
16+
left = 0
17+
18+
for point in self.points:
19+
while active and point[0] - self.points[left][0] > best_dist:
20+
bisect.insort_left(active, self.points[left][1])
21+
left += 1
22+
23+
y_lower = point[1] - best_dist
24+
y_upper = point[1] + best_dist
25+
i = bisect.bisect_left(active, y_lower)
26+
j = bisect.bisect_right(active, y_upper)
27+
28+
for y in active[i:j]:
29+
candidate = (point[0], y)
30+
dist = self.distance(point, candidate)
31+
if dist < best_dist:
32+
best_dist = dist
33+
best_pair = (point, candidate)
34+
35+
bisect.insort(active, point[1])
36+
37+
return best_pair[0], best_pair[1], best_dist
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Challenge: Use the line sweep algorithm to find the closest pair of points in a set of 2D coordinates.
2+
# This challenge requires a good understanding of geometric algorithms and spatial optimization.
3+
# Use object-oriented programming and follow the DRY principle.
4+
5+
from closest_points import ClosestPoints
6+
7+
def main():
8+
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
9+
cp = ClosestPoints(points)
10+
p1, p2, dist = cp.find_closest_pair()
11+
print(f"Closest points: {p1} and {p2} with distance {dist}")
12+
13+
if __name__ == "__main__":
14+
main()

0 commit comments

Comments
 (0)