I have two sets of Animal
objects. The distance between animals is defined using a specific algorithm that looks at their traits. I am trying to design a method to find the pair from the two sets (one from each) that minimizes the distance.
One idea I had: create a parametrized Tuple
class to pair up Animals
. Create a PriorityQueue
with a comparator to sort Tuple<Animal>
according to the distance between the two members. Then, pick the first pair from the PriorityQueue
.
Is this good design, or is it wasteful? I believe it would run in O(m+n) time, where m and n are the sizes of each collection.
If Tuple
is a parametrized class, how would it work to use a Comparator on it that only works on Animal
?
I want to use this findMinimalPair
method to create a spanning tree minimizing the distances of a graph of Animal
objects. What if I did this by continuously popping pairs off the PriorityQueue
, checking to make sure that each pair still contained one member of each collection?
Here is a basic example. Here are the distances:
A0 A1 A2 A3
A0 0 20 33 8
A1 20 0 102 73
A2 33 102 0 6
A3 8 73 6 99
Assume that the collections are:
A0
A1, A2, A3
Here would be the sorted order of tuples, by distance:
(A0, A3) - 8
(A0, A1) - 20
(A0, A2) - 33
So we see that A3 is the closest. A3 is then moved into the first collection:
A0, A3
A1, A2
Again, we check for a minimal pair:
(A3, A2) - 6
(A0, A1) - 20
(A0, A2) - 33
(A3, A1) - 73
Now A2 is taken. See how it works?
This is what I ended up doing. Comments?