I am trying to write code for the Tower of Hanoi problem. But I keep getting index out of range error in my slice inside the recursive function call. What am I doing wrong with my code?

package main

import (

func move(n int, source, target, auxiliary []int) {
	if n > 0 {
		move(n-1, source, auxiliary, target)
		curr := source[len(source)-1]
		target = append(target, curr)
		source = source[:len(source)-1]

		fmt.Printf("%v\n%v\n%v\n", source, auxiliary, target)

		move(n-1, auxiliary, target, source)

func main() {
	var (
		a = []int{3, 2, 1}
		b = []int{}
		c = []int{}
	move(3, a, c, b)

Did you try to use a debugger like delve?

I have used the debugger that comes with vs code. The problem I am having is that the length of the slice named source becomes less than 0 for some reason amidst the recursion calls.

Where you able to find the reason for this when you used the debugger?

If not, maybe try to work through your algorithm on paper: write down the state of every variable after every step and think hard about why a variable is changed the way it is changed.

Remember: the correctness of an algorithm is not related to the programming language used to implement it.

No, I could not find the reason.

I have implemented the same algorithm in Python and Kotlin. It works like a charm for those languages.

I am new to Go programming. I surmise that the change in length of the source slice after I remove the last element from it is not being transmitted amidst the recursion calls. Can this problem be due to the fact that slices are reference type?

Does this example of using slices help?


EDIT: I think this example is better.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.