【发布时间】:2013-10-09 05:40:20
【问题描述】:
我是 Scala 编程新手。 我的目标是为河内塔问题实现一个尾递归程序。 我相信它可以通过这样的递归来实现:
// Implementing a recursive function for Towers of Hanoi,where the no of disks is taken as 'n', 'from' being the Start Peg, 'to' being the End Peg, and 'via' being Intermediate Peg
def move(n: Int, from: Int, to: Int, via: Int) : Unit = { // Recursive Function
if (n == 1) {
Console.println("Move disk from pole " + from + " to pole " + to)// each move iteration printed.
}
else {
move(n - 1, from, via, to) //Moving n-1 disks from source to Intermediate
move(1, from, to, via) // Printing all the move iterations
move(n - 1, via, to, from) //Moving n and other n-1 disks to the final destination
}
}
也可以使用尾递归来实现吗?
【问题讨论】:
-
我认为没有一种简单的方法可以使尾部递归。尾递归本质上与迭代循环相同。
标签: scala tail-recursion towers-of-hanoi