I am using an ArrayList of ArrayLists for a data structure to play a game of towers of hanoi. The game is constructed and initialized as follows:
private ArrayList<ArrayList> lists = new ArrayList<ArrayList>();
private ArrayList<Integer> peg1 = new ArrayList<Integer>();
private ArrayList<Integer> peg2 = new ArrayList<Integer>();
private ArrayList<Integer> peg3 = new ArrayList<Integer>();
//Constructor
public TowersOfHanoi() {
lists.add(null);
lists.add(peg1);
lists.add(peg2);
lists.add(peg3);
}
public ArrayList initializeGame(int n) {
for (int i = 0; i < n; i++) {
peg1.add(i+1);
}
return peg1;
}
}
I am trying to use a Boolean method to do a check and make sure the user doesn't try to move a larger disc on top of a smaller disc, however, I don't understand how I would grab the the integer value stored in the arrayList. The integer values should serve as a way to gauge the diameter of the discs. I.E. 1 is smaller than two is smaller than 3 etc. This is the code I have come up with... I believe I am just getting the indexes and not the actual values of the integers stored there. How can I get the actual values?
public boolean isMoveLegal(int moveFrom, int moveTo){
ArrayList<Integer> fromPeg = lists.get(moveFrom);
int x = (fromPeg.remove(0)).intValue();
ArrayList<Integer> toPeg = lists.get(moveTo);
int y = (toPeg.get(0)).compareTo(x);
if(x<y){
System.out.println("illegal move");
}
return false;
}
This,
int y = (toPeg.get(0)).compareTo(x);
should be something like
int y = (toPeg.size() > 0) ? toPeg.get(0).intValue() : -1;
Then you can use
if (x > y) { // <-- the reverse of like you were, because the to peg is y.