From 1a63947a8a182ef7fa48f935bd707ae16bb1a841 Mon Sep 17 00:00:00 2001 From: lertlmaier Date: Thu, 8 May 2025 11:22:34 +0200 Subject: [PATCH] Line Sweep Alorithmus mit Test --- lib/linesweep.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 lib/linesweep.py diff --git a/lib/linesweep.py b/lib/linesweep.py new file mode 100644 index 0000000..b9c4663 --- /dev/null +++ b/lib/linesweep.py @@ -0,0 +1,48 @@ +from bisect import bisect_left, bisect_right +import unittest + + +def find_intersections(horizontal_segments, vertical_segments, epsilon=0.0): + horizontal_segments.sort(key=lambda h: h[0][1]) # sortiere nach y + + horizontal_ys = [] + horizontal_x_ranges = [] + for (x1, y), (x2, _) in horizontal_segments: + if x1 > x2: + x1, x2 = x2, x1 + horizontal_ys.append(y) + horizontal_x_ranges.append((x1, x2)) + + intersections = [] + + for (x, y1), (_, y2) in vertical_segments: + if y1 > y2: + y1, y2 = y2, y1 + + for idx, y in enumerate(horizontal_ys): + if y1 - epsilon <= y <= y2 + epsilon: + x_start, x_end = horizontal_x_ranges[idx] + if x_start - epsilon <= x <= x_end + epsilon: + intersections.append((x, y)) + + return intersections + +class TestStringMethods(unittest.TestCase): + + def test_sweep(self): + horizontal = [((1, 2), (5, 2)), ((3, 4), (7, 4))] + vertical = [((4, 1), (4, 5)), ((6, 3), (6, 6))] + + a = find_intersections(horizontal, vertical) + self.assertEqual( [(4,2),(4,4),(6,4)], a) + + def test_tol(self): + horizontal = [((0, 0), (10, 0))] + vertical = [((4, 0.6), (4, 5)), ((6, 0.2), (6, 6)),((8,-0.2),(8, 4))] + + b = find_intersections(horizontal, vertical, 0.5) + self.assertEqual( length(b), 2) + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file