GATE / CS ARCHIVE

GATE CSE 2000 / QUESTION 14(b)

Complete line intersection test

Algorithms · Correctness, Invariants & Design · Full GATE CSE 2000 paper

GATE 2000, Q14(b) Descriptive
Report issue

Correctness, Invariants & Design

Question 14(b), GATE 2000: Let m,n be positive integers and let the line be y=(n/m)x. Define A=mq−np for endpoint (p,q), and B=ms−nr for endpoint (r,s). Complete clash: initialize false; line4 tests A [box] 0; line5 tests B [box] 0; line6 tests A [box] 0 and B [box] 0; line7 tests A [box] 0 and B [box] 0. Each successful test sets clash=true.
Question 14(b), GATE 2000: Let m,n be positive integers and let the line be y=(n/m)x. Define A=mq−np for endpoint (p,q), and B=ms−nr for endpoint (r,s). Complete clash: initialize false; line4 tests A [box] 0; line5 tests B [box] 0; line6 tests A [box] 0 and B [box] 0; line7 tests A [box] 0 and B [box] 0. Each successful test sets clash=true.
Tap to enlarge
Answer & solution

Answer: Line4 =; line5 =; line6 < and >; line7 > and < (last two cases may be exchanged). (no official key was published)

A segment intersects the infinite line if either endpoint lies on it, or if its endpoints lie on opposite sides. The completed Pascal-style code is:

function clash(m,n,p,q,r,s: integer): Boolean;
begin
  clash := false;
  if (m*q-n*p) = 0 then clash := true;        {line 4}
  if (m*s-n*r) = 0 then clash := true;        {line 5}
  if (m*q-n*p) < 0 and (m*s-n*r) > 0 then clash := true; {6}
  if (m*q-n*p) > 0 and (m*s-n*r) < 0 then clash := true; {7}
end;

For a point interpolated along the segment with parameter t in [0,1], the signed expression is (1−t)A+tB. If A and B have opposite signs, this linear continuous function has a zero in the interval. If both have the same nonzero sign, every convex combination has that sign and there is no intersection. Endpoint equality also handles a zero-length segment lying on the line and a whole segment coincident with it. Avoid multiplying A*B merely to test the signs: that introduces extra overflow risk. As mathematical pseudocode, the original arithmetic assumes exact integer results.

Original paper, page 8