From 5afec8149d5cc14eb049c4740718d134fd2a79de Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 23 Apr 2024 13:14:33 +0200 Subject: [PATCH] task 1 --- src/Hanoi.scala | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/Hanoi.scala diff --git a/src/Hanoi.scala b/src/Hanoi.scala new file mode 100644 index 0000000..e9f3b0c --- /dev/null +++ b/src/Hanoi.scala @@ -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() + } +}