Skip to content

Instantly share code, notes, and snippets.

@eze-kiel
Last active November 2, 2022 20:01
Show Gist options
  • Save eze-kiel/df8e7c5ba92ed6452876078e16ac1adf to your computer and use it in GitHub Desktop.
Save eze-kiel/df8e7c5ba92ed6452876078e16ac1adf to your computer and use it in GitHub Desktop.
Recursive solution of the Tower of Hanoi problem, written in Go
/*
Context: https://en.wikipedia.org/wiki/Tower_of_Hanoi
Test this code: https://playground.hugoblanc.com/snippet/wryG6Tqv6aZ
*/
package main
import "fmt"
var a, b, c []int
const numOfDisks = 5 // change me, but might fail if > 10
func move(n int, src, target, aux *[]int) {
if n > 0 {
move(n-1, src, aux, target)
pop := (*src)[len((*src))-1] // get the last item
*src = (*src)[:len((*src))-1] // drop the last item from the src slice
*target = append(*target, pop)
fmt.Printf("%d\n%d\n%d\n############\n", a, b, c)
move(n-1, aux, target, src)
}
}
func main() {
for i := numOfDisks; i > 0; i-- {
a = append(a, i)
}
fmt.Printf("%d\n%d\n%d\n############\n", a, b, c)
move(len(a), &a, &c, &b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment