43 lines
1 KiB
Text
43 lines
1 KiB
Text
program range_consolidation;
|
|
tests := [
|
|
{[1.1, 2.2]},
|
|
{[6.1, 7.2], [7.2, 8.3]},
|
|
{[4, 3], [2, 1]},
|
|
{[4, 3], [2, 1], [-1, -2], [3.9, 10]},
|
|
{[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]}
|
|
];
|
|
|
|
loop for test in tests do
|
|
print(test, "->", consolidate(test));
|
|
end loop;
|
|
|
|
proc consolidate(rs);
|
|
rs := {normalize(r) : r in rs};
|
|
loop while exists r0 in rs | exists r1 in rs less r0 | r0 overlaps r1 do
|
|
rs -:= {r0, r1};
|
|
rs with:= join_ranges(r0, r1);
|
|
end loop;
|
|
return rs;
|
|
end proc;
|
|
|
|
proc normalize(r);
|
|
[r0, r1] := r;
|
|
return if r0 > r1 then [r1, r0] else [r0, r1] end;
|
|
end proc;
|
|
|
|
op overlaps(a, b);
|
|
[a0, a1] := a;
|
|
[b0, b1] := b;
|
|
if a1 > b1 then
|
|
return b1 >= a0;
|
|
else
|
|
return a1 >= b0;
|
|
end if;
|
|
end op;
|
|
|
|
proc join_ranges(a, b);
|
|
[a0, a1] := a;
|
|
[b0, b1] := b;
|
|
return [a0 min b0, a1 max b1];
|
|
end proc;
|
|
end program;
|