task 1
This commit is contained in:
parent
38c3be5740
commit
5afec8149d
32
src/Hanoi.scala
Normal file
32
src/Hanoi.scala
Normal 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()
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user