Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
However, im just not sure how to do it. Basically, my goal with this method is to return the Assistant who is available and nearest to the given location.

What I have tried:

This is what my method looks like right now, and i just cannot figure how to make it work.

Java
public Assistant findNearestAvailable(int location)
    {
        Iterator<Assistant> it = assistants.iterator();
        int closetDistance = 0;
        while(it.hasNext()){
            Assistant assistant = it.next();
            int distance = location - assistant.getLocation();
            Assistant closetAssistant;
            if(distance < assistant.getLocation() && assistant.isAvailable()){
                closetDistance++;
                }
            }
        }
        return null;
    }
Posted
Updated 20-Nov-22 5:47am
v2

1 solution

Java
if(distance < assistant.getLocation() && assistant.isAvailable()){
    closetDistance++;

That code just adds 1 to the variable, so it does not tell you anything about who is closest. You need something like:
SET closestDistance to Integer.MAX_VALUE
SET closestAssistant to NULL
FOREACH assistant in Assistants() // check all assistants
DO
    IF assistant.isAvailable() // but only the availalble ones
    THEN
        int distance = location - assistant.getLocation()
        if distance < closestDistance // if this is closer than any previous ones
        THEN
            closestDistance = distance // save the details
            closestAssistant = assistant
        FI
    FI
DONE

At the end of the loop closestDistance should contain the distance to the nearest availalble assistant, and closestAssistant will be the assistant in question.
 
Share this answer
 
Comments
CPallini 20-Nov-22 11:08am    
5.
Richard MacCutchan 20-Nov-22 11:17am    
Thank you.

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



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