15,669,438 members
0.00/5 (No votes)
See more:
Hello all, in this method i am returning the person who is available and nearest to the given location, now i am trying to return the person who has a lower ID if more than one persons are nearest to the given location. (I can call a persons ID by the method person.getIdentity().) I am unsure how to do this however. This is my method so far.

What I have tried:

Java
```<pre>public Person findNearestAvailable(int location)
{
Iterator<Person> it = persons.iterator();
int nearestDistance = Integer.MAX_VALUE;
Person nearestAssistant = null;
while(it.hasNext()) // checks all persons
{
Person person = it.next();
if(person.isAvailable()) //but only the availalble ones
{
int distance = location - person.getLocation();
if(distance < nearestDistance){
nearestDistance = distance;
nearestPerson = person;
}
}
}
return nearestPerson;
}```
Posted
Updated 20-Nov-22 11:06am

## Solution 1

Keep a reference to the last person at the same distance: each time you find a closer one, set it to that person. When you find another with the same distance, compare the ids and set it to the minimum one.
After the loop, you have the minimum distance, and lowest ID person.

Comments
OriginalGriff 21-Nov-22 8:43am
Please allow me to quote yourself:
"I can call a persons ID by the method person.getIdentity()"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Richard MacCutchan 125 Andre Oosthuizen 55 CPallini 45 Graeme_Grant 30 Dave Kreskowiak 29
 OriginalGriff 1,039 Richard MacCutchan 302 Patrice T 125 Graeme_Grant 100 CPallini 95

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900