Created
July 4, 2021 07:27
-
-
Save amuradyan/0309fc0f2e58b2fc9e78755faee8fb9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.collection.mutable.Stack | |
class Peg(val disks: Stack[Int], val name: String) | |
def solveHanoi_1(n: Int): Unit = { | |
val A = Peg(Stack[Int](1 to n: _*), "A") | |
val B = Peg(Stack[Int](), "B") | |
val C = Peg(Stack[Int](), "C") | |
val evenSeq = Seq((A, B), (A, C), (B, C)) | |
val oddSeq = Seq((A, C), (A, B), (B, C)) | |
def solve(moves: Seq[(Peg, Peg)]): Unit = { | |
var counter = 0; | |
while (C.disks.size != n) { | |
val idx = counter % 3; | |
val pegs = orderPegs(moves(idx)) | |
move(pegs) | |
counter = counter + 1; | |
} | |
} | |
def orderPegs(pegPair: (Peg, Peg)): (Peg, Peg) = { | |
val peg1 = pegPair._1 | |
val peg2 = pegPair._2 | |
if (peg1.disks.isEmpty || (!peg2.disks.isEmpty && (peg1.disks.head > peg2.disks.head))) { | |
(peg2, peg1) | |
} else { | |
pegPair | |
} | |
} | |
def move(pegs: (Peg, Peg)): Unit = { | |
val from = pegs._1 | |
val to = pegs._2 | |
val disk = from.disks.pop | |
println(s"Moving a disk of size $disk from ${from.name} to ${to.name}") | |
to.disks.push(disk) | |
} | |
if (n % 2 == 0) { | |
solve(evenSeq) | |
} else { | |
solve(oddSeq) | |
} | |
} | |
solveHanoi_1(3) | |
def solveHanoi(size: Int, from: String, to: String, extra: String): Unit = { | |
if(size != 0) { | |
solveHanoi(size - 1, from, extra, to); | |
println(s"Moving peg of size $size from $from to $to") | |
solveHanoi(size - 1, extra, to, from) | |
} | |
} | |
solveHanoi(3, "A", "B", "C") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment