Search code examples
javapath-findinga-star

Comparing multiple returns from method


i have an array with multiple Nodes, these each have their H, G and F scores.

I get the H and G scores from a method called calculateGscore() and calculateHscore() which both return a double, the F score is H+G;

I have an ArrayList with open Nodes and i have to find the node with the lowest F score, but i dont know how to do this, the open arraylist can have 1 to 4 Nodes in it, no diaganol movement allowed.

What i have now is a for loop like:

 for(int i = 1; i < open.size(); i++){
            Gscore = open.get(i).getGscore(); // these methods are in the Node class.
            Hscore = open.get(i).getHscore();
            Fscore = Gscore + Hscore;

            if(Fscore < (calculateGscore(open.get(i-1)) + calculateHscore(open.get(i-1)))){          // these methods are in the pathFinder class.
                closed.add(open.get(i));
            }
            else{
                closed.add(open.get(i-1));
                open.remove(i-1);
            }
        }

but this doesnt work if there are 4 nodes in the open list, then it adds 2 nodes to the closed list instead of the only lowest.

I have this as an assignment so i cant change any code in the Node class, only in the pathfinder class.


Solution

  • Use the following instead:

    double minFscore = open.get(0).getGscore() + open.get(0).getHscore();
    Node minScoreNode = open.get(0);
    
    for(int i = 1; i < open.size(); i++) {
        Gscore = open.get(i).getGscore(); // these methods are in the Node class.
        Hscore = open.get(i).getHscore();
        Fscore = Gscore + Hscore;
    
        if (Fscore < minFscore) {
             minScoreNode = open.get(i);
             minFscore = Fscore;
        }
    }
    
    open.remove(minScoreNode);
    closed.add(minScoreNode);
    

    This will loop through each node, find the node with the minimum fScore and will then move that node from the open list to the closed list. Your problem was that you were trying to add and remove before looking at the entire list.