This commit is contained in:
Louis Heredero 2024-04-23 13:14:33 +02:00
parent 38c3be5740
commit 5afec8149d
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7

32
src/Hanoi.scala Normal file
View File

@ -0,0 +1,32 @@
import scala.collection.mutable
class Hanoi(val n: Int, val left: Char, val mid: Char, val right: Char) {
val lists: mutable.HashMap[Char, mutable.Stack[Int]] = new mutable.HashMap()
lists(left) = mutable.Stack.range(1, n + 1)
lists(mid) = mutable.Stack.empty
lists(right) = mutable.Stack.empty
def move(from: Char, to: Char): Unit = {
val i: Int = lists(from).pop()
println(s"Moving disk $i from $from->$to")
lists(to).push(i)
}
def solve(): Unit = {
hanoi(n, left, mid, right)
}
private def hanoi(n: Int, start: Char, aux: Char, end: Char): Unit = {
if (n == 0) return
hanoi(n - 1, start, end, aux)
move(start, end)
hanoi(n - 1, aux, start, end)
}
}
object Hanoi {
def main(args: Array[String]): Unit = {
val hanoi: Hanoi = new Hanoi(3, 'A', 'B', 'C')
hanoi.solve()
}
}