Introduction
The Hausdorff distance measures the difference between two subsets of a metric space.
Intuitively, a metric space is just some set with a built-in distance function; in this challenge, we will use natural numbers with the ordinary distance d(a, b) := abs(a - b)
.
The Hausdorff distance between two non-empty finite sets A
and B
is given by
max(max(min(d(a, b) for b in B) for a in A),
max(min(d(a, b) for a in A) for b in B))
in Python-like notation.
The Hausdorff distance can be computed by finding the element of A
for which the distance to the nearest element of B
is maximal, and the element of B
for which the distance to the nearest element of A
is maximal, and then taking the maximum of these distances.
In other words, if the Hausdorff distance is d
, then every element of A
is within distance d
of some element of B
, and vice versa.
Input
Your input is a single list of integers.
It only contains the elements 0,1,2,3
, which signify whether the given index of the list is an element of neither A
nor B
, only A
, only B
, or both A
and B
.
For example, the input [0,1,1,0,2,3]
means that A = {1,2,5}
and B = {4,5}
, if we use 0-based indexing (which makes no difference, as our metrics are translation invariant).
Output
Your output is the Hausdorff distance between A
and B
; in the above example, it is 3
.
If either set is empty, then the distance is not defined, and you shall return -1
.
Rules
You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.
Test Cases
[] -> -1
[0] -> -1
[0,1,0] -> -1
[2,0,0,2] -> -1
[0,1,2,3] -> 1
[0,3,3,0,0,0,0,3] -> 0
[1,0,0,1,0,0,1,3,1] -> 7
[1,0,0,0,0,3,0,0,0,0,2] -> 5
[0,1,1,3,1,3,2,1,1,3,0,3] -> 2
[2,2,2,1,2,0,3,1,3,1,0,3] -> 3
[1,3,0,2,0,2,2,1,0,3,2,1,1,2,2] -> 2
[1,0,1,1,2,0,1,2,3,1,0,0,0,1,2,0] -> 4
max(max(min(d(a, b) for b in B) for a in A))
should be sufficient. This is becaused(a,b)
returns the absolute value, and therefore both max functions will return the same number every time. \$\endgroup\$A
is very close to one ofB
, but there are elements ofB
very far fromA
(for example, ifA
is a subset ofB
). In that case, the short formula is incorrect. \$\endgroup\$