Golang program for implementation of Tower of Hanoi Algorithm
Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings. 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. Here is source code of the Go Program to implement Tower of Hanoi Algorithm
Example
package main
import "fmt"
type solver interface {
play(int)
}
// towers is example of type satisfying solver interface
type towers struct {
// an empty struct
}
// play is sole method required to implement solver type
func (t *towers) play(n int) {
t.moveN(n, 1, 2, 3)
}
// recursive algorithm
func (t *towers) moveN(n, from, to, via int) {
if n > 0 {
t.moveN(n-1, from, via, to)
t.moveM(from, to)
t.moveN(n-1, via, to, from)
}
}
func (t *towers) moveM(from, to int) {
fmt.Println("Move disk from rod", from, "to rod", to)
}
func main() {
var t solver
t = new(towers) // type towers must satisfy solver interface
t.play(4)
}
Output
Move disk from rod 1 to rod 3
Move disk from rod 1 to rod 2
Move disk from rod 3 to rod 2
Move disk from rod 1 to rod 3
Move disk from rod 2 to rod 1
Move disk from rod 2 to rod 3
Move disk from rod 1 to rod 3
Move disk from rod 1 to rod 2
Move disk from rod 3 to rod 2
Move disk from rod 3 to rod 1
Move disk from rod 2 to rod 1
Move disk from rod 3 to rod 2
Move disk from rod 1 to rod 3
Move disk from rod 1 to rod 2
Move disk from rod 3 to rod 2
Most Helpful This Week
Golang program to generate number of slices permutations of number entered by user
How to get first and last element of slice in Golang?
Nested Struct Type
How to add items to Slice using append function in Golang?
Go program to find CNAME record of a domain
GO Program to Check Whether a Number is Palindrome or Not