To solve the Towers of Hanoi from an arbitrary position, you can use a recursive procedure similar to the standard solution that works from the standard start position.
It just has to be a little more general.
Write a recursive procedure moveDisks(maxSize,targetPeg) that moves all the disks with size <= maxSize to the peg targetPeg, like this:
Find the largest disk m such that m.size <= maxSize and m is not on targetPeg. If there is no such disk, then return, because all the disks with size <= maxSize are already in the right place.
Let sourcePeg be the peg where m is currently, and let otherPeg be the the peg that isn't sourcePeg or targetPeg.
Call moveDisks(m.size-1, otherPeg) recursively to get the smaller disks out of the way.
Move m from sourcePeg to targetPeg.
Call moveDisks(m.size-1, targetPeg) recursively to put the smaller disks where they belong.
In Java, I would write it like this:
/**
* Solve towers of hanoi from an arbitrary position
*
* @param diskPositions the current peg for each disk (0, 1, or 2) in increasing
* order of size. This will be modified
* @param disksToMove number of smallest disks to moves
* @param targetPeg target peg for disks to move
*/
static void moveDisks(int[] diskPositions, int disksToMove, int targetPeg)
{
for (int badDisk = disksToMove-1; badDisk >= 0; --badDisk) {
int currentPeg = diskPositions[badDisk];
if (currentPeg != targetPeg) {
// found the largest disk on the wrong peg
// sum of the peg numbers is 3, so to find the other one:
int otherPeg = 3 - targetPeg - currentPeg;
// before we can move badDisk, we have to get the smaller
// ones out of the way
moveDisks(diskPositions, badDisk, otherPeg);
// Move
diskPositions[badDisk] = targetPeg;
System.out.println(
"Move " + badDisk + " from " + currentPeg + " to " + targetPeg
);
//Now we can put the smaller ones in the right place
moveDisks(diskPositions, badDisk, targetPeg);
break;
}
}
}
... well, I wouldn't write it exactly like this in real life. You can actually remove the second recursive call and the break, because the remaining iterations in the loop will accomplish the same thing.