POOLab17-Recursion/src/Hanoi.scala
2024-04-30 13:20:08 +02:00

33 lines
841 B
Scala

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()
}
}