What is Tower of Hanoi and How it works ?
The Tower of Hanoi is a mathematical puzzle consisting of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
- No disk may be placed on top of a smaller disk.
The puzzle is often used to teach computer programming, algorithm design, and recursion. It is also a popular puzzle among mathematicians and puzzle enthusiasts. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2^n – 1, where n is the number of disks.
Steps to create Tower of Hanoi in Kotlin.
Step 1: Create a function which will take 4 argument x, A, B, C. where x is number of disks, A is a source rod, B is a auxiliary rod and C is destination rod.
fun toh(x: Int, A: String, B: String, C: String){
}
Step 2: how check if x = 1 the print move a -> c and terminate the program
Step 3: Else call toh with x = x-1 and change the rod names
fun toh(x: Int, A: String, B: String, C: String){
if(x==1) {
println("$A to $C")
return
}
toh(x-1,A,C,B)
println("$A to $C")
toh(x-1,B,A,C)
}
Step 4: Call the function from main function by providing the each value
fun main(){
val x = 3
toh(x,"A","B","C")
}
fun toh(x: Int, A: String, B: String, C: String){
if(x==1) {
println("$A to $C")
return
}
toh(x-1,A,C,B)
println("$A to $C")
toh(x-1,B,A,C)
}
You can run the code by clicking on play button on the right top of the final code.