Determining Number of Line Segment Intersections

32 views Asked by At

Given a set of line segments, determine the number of intersections. Input starts with a number N and is followed by N sets of input. For each set of input, the first number indicates the number of line segments. Each line segment is represented by 4 numbers (x1 y1 x2 y2) indicating the two endpoints of the line segments. Collinear and Overlapping line segments are considered to be non-intersecting. Output the number of intersections.

def count_intersections(segments):
    intersections = 0

    for i in range(len(segments) - 1):
        x1, y1, x2, y2 = segments[i]

        for j in range(i + 1, len(segments)):
            x3, y3, x4, y4 = segments[j]

            # Calculate slopes and handle the case where the denominator    is zero
            slope1 = (y2 - y1) / (x2 - x1) if x1 != x2 else float('inf')
            slope2 = (y4 - y3) / (x3 - x4) if x3 != x4 else float('inf')

            if slope1 != slope2:
                # Calculate intersection point
                intersection_x = (
                    (slope1 * x1 - slope2 * x3) + (y3 - y1)
                ) / (slope1 - slope2)
                intersection_y = slope1 * (intersection_x - x1) + y1

                # Check if intersection point lies within the line segments
                if (
                    min(x1, x2) <= intersection_x <= max(x1, x2)
                    and min(y1, y2) <= intersection_y <= max(y1, y2)
                    and min(x3, x4) <= intersection_x <= max(x3, x4)
                    and min(y3, y4) <= intersection_y <= max(y3, y4)
                ):
                    intersections += 1

    return intersections

def main():
    num_sets = int(input())
    results = []

    for _ in range(num_sets):
        num_segments = int(input())
        segments = [list(map(int, input().split())) for _ in range(num_segments)]

        intersections = count_intersections(segments)
        results.append(intersections)

    for result in results:
        print(result)

if __name__ == "__main__":
    main()

I am expecting a sample output of 2 3. But what resulted is 0 0.

0

There are 0 answers