Using random function in selecting an object if two same distance values

I have an ArrayList unsolvedOutlets containing object Outlet that has attributes longitude and latitude.

Using the longitude and latitude of Outlet objects in ArrayList unsolvedOutlets, I need to find the smallest distance in that list using the distance formula : SQRT(((X2 - X1)^2)+(Y2-Y1)^2), wherein (X1, Y1) are given. I use Collections.min(list) in finding the smallest distance.

My problem is if there are two or more values with the same smallest distance, I'd have to randomly select one from them.

Code:

ArrayList<Double> distances = new ArrayList<Double>();
Double smallestDistance = 0.0;
for (int i = 0; i < unsolvedOutlets.size(); i++) {
    distances.add(Math.sqrt(
        (unsolvedOutlets.get(i).getLatitude() - currSolved.getLatitude())*
        (unsolvedOutlets.get(i).getLatitude() - currSolved.getLatitude())+
        (unsolvedOutlets.get(i).getLongitude() - currSolved.getLongitude())*
        (unsolvedOutlets.get(i).getLongitude() - currSolved.getLongitude())));
    distances.add(0.0); //added this to test 
    distances.add(0.0); //added this to test 
    smallestDistance = Collections.min(distances);   
    System.out.println(smallestDistance);                                     
}          

The outcome in the console would print out 0.0 but it wont stop. Is there a way to know if there are multiple values with same smallest value. Then I'd incorporate the Random function. Did that make sense? lol but if anyone would have the logic for that, it would be really helpful!!

Thank you!

Jon Skeet
people
quotationmark

Note: I believe fabian's solution is superior to this, but I've kept it around to demonstrate that there are many different ways of implementing this...

I would probably:

  • Create a new type which contained the distance from the outlet as well as the outlet (or just the square of the distance), or use a generic Pair type for the same purpose
  • Map (using Stream.map) the original list to a list of these pairs
  • Order by the distance or square-of-distance
  • Look through the sorted list until you find a distance which isn't the same as the first one in the list

You then know how many - and which - outlets have the same distance.

Another option would be to simply shuffle the original collection, then sort the result by distance, then take the first element - that way even if multiple of them do have the same distance, you'll be taking a random one of those.

JB Nizet's option of "find the minimum, then perform a second scan to find all those with that distance" would be fine too - and quite possibly simpler :) Lots of options...

people

See more on this question at Stackoverflow