Kotlin – Tower of Hanoi
The Tower of Hanoi is a classic problem in computer science and mathematics that involves moving a stack of disks from one rod to another. The rules are simple: only one disk can be moved at a time, and a larger disk cannot be placed on top of a smaller disk. This tutorial will guide you through solving the Tower of Hanoi problem using recursion in Kotlin.
Step 1: Define the Tower of Hanoi Function
Create a recursive function to solve the Tower of Hanoi problem. The function will take three parameters: the number of disks to be moved (n), the rod from which the disks are initially stacked (source), the auxiliary rod (auxiliary), and the rod to which the disks should be moved (destination).
fun towerOfHanoi(n: Int, source: Char, auxiliary: Char, destination: Char) {
if (n == 1) {
println("Move disk 1 from $source to $destination")
return
}
towerOfHanoi(n - 1, source, destination, auxiliary)
println("Move disk $n from $source to $destination")
towerOfHanoi(n - 1, auxiliary, source, destination)
}
Step 2: Use the Tower of Hanoi Function
Call the towerOfHanoi
function with the number of disks and the rod labels (A, B, C) representing the source, auxiliary, and destination rods.
fun main() {
val n = 3 // Change the number of disks as needed
towerOfHanoi(n, 'A', 'B', 'C')
}
Complete Kotlin Program
The following is the complete Kotlin program to solve the Tower of Hanoi problem.
Kotlin Program
fun towerOfHanoi(n: Int, source: Char, auxiliary: Char, destination: Char) {
if (n == 1) {
println("Move disk 1 from $source to $destination")
return
}
towerOfHanoi(n - 1, source, destination, auxiliary)
println("Move disk $n from $source to $destination")
towerOfHanoi(n - 1, auxiliary, source, destination)
}
fun main() {
val n = 3 // Change the number of disks as needed
towerOfHanoi(n, 'A', 'B', 'C')
}
Output
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Summary
By following these steps and using recursion, you can solve the Tower of Hanoi problem in Kotlin. The program will display the sequence of moves required to move all the disks from the source rod to the destination rod while following the rules of the Tower of Hanoi puzzle.