golang – string permutation – slice bounds out of range

huangapple go评论76阅读模式
英文:

golang - string permutation - slice bounds out of range

问题

这是这个问题的Go Playground代码。

我正在尝试使用递归编写一个Golang字符串排列。排列函数接受两个参数,一个是空字符串("")的前缀,另一个是字符串"abc"。代码如下:

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])
        }
    }
}

当我运行这段代码时,我得到了预期的值3,2,1,0。我成功地得到了"abc",但是然后我得到了一个"panic: runtime error: slice bounds out of range"的错误。

它从未显示第二轮的3,2,1,0,所以它甚至没有到达b的组合。我觉得如果出现错误,应该是在字符串的c部分,但是由于它甚至没有到达b部分,我不确定出了什么问题。

英文:

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 (&quot;&quot;) and str which is "abc". The code is below

func main() {
	str := &quot;abc&quot;
	perm(&quot;&quot;, str)
}

func perm(prefix string, str string) {
	n := len(str)
	fmt.Println(n)
	if n == 0 {
		fmt.Println(prefix)
	} else {
		for i := 0; i &lt; 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.

答案1

得分: 1

简单示例:

for i := 0; i < n; n++ {
                   ^^^
                    ?

n 替换为 ii 应该从 0 变化到 n-1

结果展示

英文:

Simple:

for i := 0; i &lt; n; n++ {
                   ^^^
                    ?

Replace n by i, which is supposed to go from 0 to n-1.

Resulting playground.

huangapple
  • 本文由 发表于 2016年10月29日 12:03:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/40315918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定