Is there a way to incrementally increase the count for the Tower of Hanoi challenge?
At the moment, the count isn't incrementally increasing. Interestingly, it starts at five and hops around. See the output below.
I tried adding a let count = 0
within the function and adding ++count
within the IF statement and outside the recursive function to no avail.
Working code block:
const move = (n, source, destination, buffer, count) => {
// Verify that there are disks.
if (n > 0) {
// Move one disk to buffer rod.
move(n - 1, source, buffer, destination, ++count);
// Move nth disk from source to destination.
destination.push(source.pop())
// Display progress
console.log(count, A, B, C, "\n--------------------------")
// Move the disk (n - 1) from the buffer to the destination.
move(n - 1, buffer, destination, source, ++count);
}
};
// Disk starting position
const A = [5, 4, 3, 2, 1]
const B = []
const C = []
// Invoke
move(5, A, C, B, 0);
Output:
5 [ 5, 4, 3, 2 ] [] [ 1 ]
--------------------------
4 [ 5, 4, 3 ] [ 2 ] [ 1 ]
--------------------------
6 [ 5, 4, 3 ] [ 2, 1 ] []
--------------------------
3 [ 5, 4 ] [ 2, 1 ] [ 3 ]
--------------------------
6 [ 5, 4, 1 ] [ 2 ] [ 3 ]
--------------------------
5 [ 5, 4, 1 ] [] [ 3, 2 ]
--------------------------
7 [ 5, 4 ] [] [ 3, 2, 1 ]
--------------------------
2 [ 5 ] [ 4 ] [ 3, 2, 1 ]
--------------------------
6 [ 5 ] [ 4, 1 ] [ 3, 2 ]
--------------------------
5 [ 5, 2 ] [ 4, 1 ] [ 3 ]
--------------------------
7 [ 5, 2, 1 ] [ 4 ] [ 3 ]
--------------------------
4 [ 5, 2, 1 ] [ 4, 3 ] []
--------------------------
7 [ 5, 2 ] [ 4, 3 ] [ 1 ]
--------------------------
6 [ 5 ] [ 4, 3, 2 ] [ 1 ]
--------------------------