Here is the Go Playground code for this problem.
I am trying to write a golang string permutation using recursion.
The permutation function takes two arguments, prefix which is an empty string (""
) and str
which is "abc
". The code is below
func main() {
str := "abc"
perm("", str)
}
func perm(prefix string, str string) {
n := len(str)
fmt.Println(n)
if n == 0 {
fmt.Println(prefix)
} else {
for i := 0; i < n; n++ {
perm(prefix+str[i:i+1], str[0:i]+str[(i+1):n])
}
}
}
When I run this code, I am shown 3,2,1,0 for the value of n as expected.
I successfully get "abc
" but then I get a "panic: runtime error: slice bounds out of range
" error.
It never shows the second round of 3,2,1,0 so it doesn't even get to the b
combinations. I feel like if an error would occur is when it gets to the c
portion of the string but since it doesn't even get to the b
portion, I am not sure what is wrong.
Simple:
for i := 0; i < n; n++ {
^^^
?
Replace n
by i
, which is supposed to go from 0
to n-1
.