'Implementing a Fifteen Puzzle AStar pseudo code into a java code
We have been given a task to do the "TODO" part of the following java file:
1 To do part
https://courses.cs.duke.edu/spring09/cps170/AStar.java
https://courses.cs.duke.edu/spring09/cps170/Node.java
The 3 To do part here is the isGoal(), evaluateHeuristic(), and generateChildren() methods.
https://courses.cs.duke.edu/spring09/cps170/FifteensNode.java
I am having a trouble converting the pseudocode inside the AStar.java's run() function. Below is the pseudocode:
* create a TreeSet and provide it with the node's comparator like this:
* TreeSet<Node> fringe = new TreeSet<Node>(rootNode.getComparator());
* General algorithm:
* 1. Create an empty fringe, as above
* 2. Put the root search node to the fringe
* 3. While fringe is not empty:
* 4. Get the first search node from the fringe
* 5. Remove that node from the fringe
* 6. If that's a goal node, print the solution using node.printSolution()
* 7. Otherwise, generate the successor nodes using node.generateChildren
* 8. Add all the generated nodes to the fringe
* 9. If no solution was found, print "No solution found."
This is how I implemented the code initially:
public static void run(Node rootNode) {
// TODO: add your code here
Node node;
TreeSet<Node> fringe = new TreeSet<Node>(rootNode.getComparator());
fringe.add(rootNode);
while(!fringe.isEmpty()){
node = fringe.first();
fringe.remove(node);
if(node.isGoal()){
node.printSolution();
return;
}
node.generateChildren();
fringe.add(node);
}
System.out.print("No solution found.");
}
But it does not make any sense since the node.generateChildren() inside the FifteenNodes.java should return a List<FifteenNode> so I tried to change this part
node.generateChildren();
fringe.add(node);
into this
List<Node> nodes; //Created before the while loop.
nodes = node.generateChildren();
fringe.add(nodes);
But it caused an conversion error so I red the TreeSet class and it provided a fringe.addAll() function so yet again I changed the previous part of the code into this:
fringe.addAll(node.generateChildren());
However it loops forever without stopping I don't know the reason why it is happening so I thought maybe my implementation of the pseudocode is wrong and wanted to know on how should I Implement the pseudo code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
