有没有办法逐步增加河内塔挑战的数量?
目前,计数并没有逐步增加。有趣的是,它从五点开始跳来跳去。请参阅下面的输出。
我尝试在函数中添加let count = 0
,并在 IF 语句内和递归函数外部添加++count
,但无济于事。
工作代码块:
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);
输出:
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 ]
--------------------------
返回count
的值并将其赋回变量。
const move = (n, source, destination, buffer, count) => {
// Verify that there are disks.
if (n > 0) {
// Move one disk to buffer rod.
count = move(n - 1, source, buffer, destination, ++count);
// Move nth disk from source to destination.
destination.push(source.pop())
// Display progress
console.log(count, JSON.stringify(A), JSON.stringify(B), JSON.stringify(C), "n--------------------------")
// Move the disk (n - 1) from the buffer to the destination.
count = move(n - 1, buffer, destination, source, ++count);
}
return count;
};
// Invocate
const A = [5, 4, 3, 2, 1]
const B = []
const C = []
move(5, A, C, B, 0);