I was trying to learn about some implementations of the tower of Hanoi and the algorithm behind it and I came across a Stack Overflow user's answer from 2020, and I'm learning a thing or two from it.
Here is the link to that answer (its the one with the checkbox on it): Solving tower of Hanoi with given arrangements
and here is the code
public static long stepsRemaining(int[] diskPos) {
int size = 0;
int target = 1;
int m = 0;
int[] targets = new int[diskPos.length];
for (int i = diskPos.length - 1; i >= 0; i--) {
targets[i] = target;
if (diskPos[i] != target) {
target = 3 - target - diskPos[i];
}
size++;
}
while (m < diskPos.length) {
for (m = 0; m < diskPos.length; m++) {
if (targets[m] != diskPos[m]) {
target = targets[m];
System.out.format("move disk %d from rod %d to %d.\n", m, targets[m], target);
diskPos[m] = target;
for (int j = m - 1; j >= 0; j--) {
targets[j] = target;
target = 3 - target - diskPos[j];
}
break;
}
size++;
}
}
return size;
}
I'm trying to return the number of steps remaining, an int, to complete shifting the discs from their assigned pegs, to peg 1. The code I have seen and provided does exactly as I wanted but it only lists out the steps needed to complete the transfer, not the number of steps.
I've tried to implement int size over each for loop in hopes of calculating how many times a move was made, but to no avail. Can anyone please explain how can I do that?