Im working on a code to implement different search functions to solve the Farmer Wolf Goat Cabbage problem. We were given several classes that our main and FarmerWolfGoatCabbage class implemented. One of the classes, AbstractSolver includes the line
Iterable<AState> moves = s.getPossibleMoves();
for (AState move : moves)
if (!closed.contains(move))
addState(move);
Here is my FarmerWolfGoatCabbage class.I basically want to translate the following function
public DepthFirstSolver getPossibleMoves1(){
DepthFirstSolver moves = null;
//use getOpposite() and addIfSafe
FarmerWolfGoatState fwgsParent = new FarmerWolfGoatState();
FarmerWolfGoatState fwgsChild = null;
int hash;
// the farmer's current position before crossing the river
Side farmerCurrent = this.farmer;
if(this.wolf == farmerCurrent){
fwgsChild = new FarmerWolfGoatState(this, this.getOpposite(this.farmer),
this.getOpposite(this.wolf), this.goat, this.cabbage);
hash = fwgsChild.hashCode();
if(addIfSafe(hash))
moves.addState(fwgsChild);
System.out.println("W");
}
if(this.cabbage == farmerCurrent){
fwgsChild = new FarmerWolfGoatState(this, this.getOpposite(this.farmer),
this.wolf, this.goat, this.getOpposite(this.cabbage));
hash = fwgsChild.hashCode();
if(addIfSafe(hash))
moves.addState(fwgsChild);
System.out.println("C");
}
if(this.goat == farmerCurrent){
fwgsChild = new FarmerWolfGoatState(this, this.getOpposite(this.farmer),
this.wolf, this.getOpposite(this.goat), this.cabbage);
hash = fwgsChild.hashCode();
fwgsChild.getPosition();
//
if (fwgsChild == null)
System.out.println("NULL");
if(addIfSafe(hash))
//moves.addState(fwgsChild);
System.out.println("G");
}
return moves;
}
into a similar function but with the Iterable return type
public Iterable<AState> getPossibleMoves()
{
}
Iterable
is an interface:http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html
Your
FirstDepthSolver
class needs to implement that interface as that is what you're returning fromgetPossibleMoves1()
. Subsequently this means you're going to have to implementIterator
(or else store whatever it is you're needing to iterate over in a java Collection that already provides an interator, and return that).I suspect that's what the assignment is trying to get you to do in addition to solving the problem at hand.
This SO question should be of some help: How can I implement the Iterable interface?