'an object where it has a parent and an action and each parent has a parent and an action
How can I do this in Java
public class State implements Comparable<State> {
//other attbs;
State parent;
String actionFromParent;
// other code
}
where x is an object of type State and each parent itself has an action from parent. I want to do this until I have actionFromParent == null.
I don't know how many parents there are. I'm using this to print the path for A* algorithm. I'm stuck at printing the path after x (state currentnode) satisfies the goal, I print all actionfromparents of its child nodes.
System.out.println(x.actionFromParent);
System.out.println(x.parent.actionFromParent);
System.out.println(x.parent.parent.actionFromParent);
System.out.println(x.parent.parent.parent.actionFromParent);
.....
until (x.parent.parent.parent.....parent.actionFromParent == null)
Solution 1:[1]
You can use a while loop or a recursive function.
With a while loop:
State x = theState;
while (x != null && x.actionFromParent != null) {
System.out.println(x.actionFromParent);
x = x.parent;
}
With a recursive function:
public static void printActionsFromParent(State x) {
if (x != null && x.actionFromParent != null) {
System.out.println(x.actionFromParent);
printActionsFromParent(x.parent);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
