3

I am trying to implement the UCS algorithm for a game in Java and I am now in the stage where I need to calculate the costs of each state.

I made a Node class with 4 fields (a Table state, double cost, a Node parent and an ArrayList<Node> children) where i have a private static double calculateCost(Node starting, Node next) method, which returns the cost of transitioning from the starting node to the next node.

Ignore the Table class, there is no need to explain what it does.

I also made the following generateChildren() method:

public void generateChildren(){
    ArrayList<Table> allStates = this.state.generateMoves();

    for(Table state : allStates){
        Node child = new Node(state, calculateCost(this, ???), this);

        children.add(child);
    }
}

It generates all the possible moves from a given state, and for each move it creates a child.

What I want is to pass child as the second argument of the calculateCost(), so that this object is the starting Node, and the child is the next Node. Is it possible at all?

  • 2
    No, this does not seem possible. There is an alternative way I can think of. Create the child node using only the state and this parameters. Then calculate cost and call a setter method in the child node to set the cost. – AKSingh Jul 01 '23 at 14:00
  • Stelios, have you read my answer? – MorganS42 Jul 15 '23 at 02:08

1 Answers1

1

You could completely remove the calculateCost(this, ???) parameter, and instead move it into the Node constructor. You haven't posted what the Node constructor currently looks like, so the below code is simply a template that you can map to your current solution:

class Node {
    * before constructor *

    Node(Table state, Node parent) {
        this.state = state;
        this.parent = parent;

        this.cost = calculateCost(parent, this);

        * rest of constructor *
    }

    * after constructor *
}

This should give the desired effect. Your generateChildren method would now look like:

public void generateChildren(){
    ArrayList<Table> allStates = this.state.generateMoves();

    for(Table state : allStates){
        Node child = new Node(state, this);

        children.add(child);
    }
}
MorganS42
  • 656
  • 4
  • 21