Overlap (X, Y) := if (X1 <= Y1) then (Y1 <= X2) else (X1 <= Y2).
PROOF:
Consider the case when X precedes, or is left aligned with, Y, i.e., X1 <= Y1. Then either Y starts inside, or at the end of, X, i.e. Y1 <= X2; or else Y is away from X. The first condition is overlap; the second, not.
In the complementary case when Y precedes X, the same logic applies to the swapped entities.
So,
Overlap (X, Y) := if (X1 <= Y1) then (Y1 <= X2) else Overlap (Y, X).
But this does not seem quite right. On the recursive call, the first test is redundant, as we already know the relative position of the entities from the first test on the first call. So, we really only need to test for the second condition, which, upon swapping, is (X1 <= Y2). So,
Overlap (X, Y) := if (X1 <= Y1) then (Y1 <= X2) else (X1 <= Y2).
QED.
Implementation in Ada:
type Range_T is array (1 .. 2) of Integer;
function Overlap (X, Y: Range_T) return Boolean is
(if X(1) <= Y(1) then Y(1) <= X(2) else X(1) <= Y(2));
Test program:
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Range_T is array (1 .. 2) of Integer;
function Overlap (X, Y: Range_T) return Boolean is
(if X(1) <= Y(1) then Y(1) <= X(2) else X(1) <= Y(2));
function Img (X: Range_T) return String is
(" [" & X(1)'Img & X(2)'Img & " ] ");
procedure Test (X, Y: Range_T; Expect: Boolean) is
B: Boolean := Overlap (X, Y);
begin
Put_Line
(Img (X) & " and " & Img (Y) &
(if B then " overlap .......... "
else " do not overlap ... ") &
(if B = Expect then "PASS" else "FAIL"));
end;
begin
Test ( (1, 2), (2, 3), True); -- chained
Test ( (2, 3), (1, 2), True);
Test ( (4, 9), (5, 7), True); -- inside
Test ( (5, 7), (4, 9), True);
Test ( (1, 5), (3, 7), True); -- proper overlap
Test ( (3, 7), (1, 5), True);
Test ( (1, 2), (3, 4), False); -- back to back
Test ( (3, 4), (1, 2), False);
Test ( (1, 2), (5, 7), False); -- disjoint
Test ( (5, 7), (1, 2), False);
end;
Output of above program:
[ 1 2 ] and [ 2 3 ] overlap .......... PASS
[ 2 3 ] and [ 1 2 ] overlap .......... PASS
[ 4 9 ] and [ 5 7 ] overlap .......... PASS
[ 5 7 ] and [ 4 9 ] overlap .......... PASS
[ 1 5 ] and [ 3 7 ] overlap .......... PASS
[ 3 7 ] and [ 1 5 ] overlap .......... PASS
[ 1 2 ] and [ 3 4 ] do not overlap ... PASS
[ 3 4 ] and [ 1 2 ] do not overlap ... PASS
[ 1 2 ] and [ 5 7 ] do not overlap ... PASS
[ 5 7 ] and [ 1 2 ] do not overlap ... PASS