Skip to content

Instantly share code, notes, and snippets.

@bgbaroo
Created December 3, 2022 19:01
Show Gist options
  • Save bgbaroo/edd705d4123bd9a5b83f6531f8ccfd3c to your computer and use it in GitHub Desktop.
Save bgbaroo/edd705d4123bd9a5b83f6531f8ccfd3c to your computer and use it in GitHub Desktop.
Tower of Hanoi
package main
import "fmt"
const (
// Rods are 1, 2, and 3
// Given src and dst, the other buffer rod is (1+2+3) - (src + dst) = 6 - (src + dst)
rod1 = iota + 1
rod2
rod3
sumRod = rod1 + rod2 + rod3
)
func main() {
towerOfHanoi(4, 1, 3)
}
func towerOfHanoi(n, src, dst int) {
if n == 1 {
move(src, dst)
return
}
buf := sumRod - (src + dst)
towerOfHanoi(n-1, src, buf) // Move the "top disks" to buf
towerOfHanoi(1, src, dst) // Move the bottom (largest disk) to dst
towerOfHanoi(n-1, buf, dst) // Move the other disks from buf to dst
}
func move(start, end int) {
fmt.Println(start, "->", end)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment