Go切片和循环:在每次循环中,通过减少1个项目来多次遍历切片项。

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

Go slices and loops: Multilple loop through slice items while reducing the items with 1 each on each loop

问题

我有一个整数切片,我想要多次循环遍历它,但每次进行另一个循环时,我希望从父循环中排除该项。

类似这样的代码:

func main() {
    as := []int{0, 1, 2, 3}
    for i, a := range as {
        bs := make([]int, len(as))
        copy(bs, as)
        bs = append(bs[:i], bs[i+1:]...)
        for i, b := range bs {
            cs := make([]int, len(bs))
            copy(cs, bs)
            cs = append(cs[:i], cs[i+1:]...)
            for i, c := range cs {
                ds := make([]int, len(cs))
                copy(ds, cs)
                ds = append(ds[:i], ds[i+1:]...)
                for _, d := range ds {
                    fmt.Println(a, b, c, d)
                }
            }
        }
    }
}

这段代码的输出是:

0123
0132
0213
0231
0312
0321
1023
1032
1203
1230
1302
1320
2013
2031
2103
2130
2301
2310
3012
3021
3102
3120
3201
3210

这正是我想要的。但是这段代码看起来不太好。我必须在删除一个项之前多次复制切片,然后在该切片上循环遍历项。有没有更好、更简洁的方法来实现我在这里做的事情?我将对一个看起来像这样的切片执行相同的操作:[]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

我不认为像我这样写每个循环10次是一个好方法。有没有建议我如何做到这一点的方法?

英文:

I have a slice of ints that I want to loop through multiple times, but each time I do another loop, I want to exclude the item from the parent loop.

Something like this:

func main() {
	as := []int{0, 1, 2, 3}
	for i, a := range as {
		bs := make([]int, len(as))
		copy(bs, as)
		bs = append(bs[:i], bs[i+1:]...)
		for i, b := range bs {
			cs := make([]int, len(bs))
			copy(cs, bs)
			cs = append(cs[:i], cs[i+1:]...)
			for i, c := range cs {
				ds := make([]int, len(cs))
				copy(ds, cs)
				ds = append(ds[:i], ds[i+1:]...)
				for _, d := range ds {
					fmt.Println(a, b, c, d)
				}
			}
		}
	}
}

The output of this code is:

0123
0132
0213
0231
0312
0321
1023
1032
1203
1230
1302
1320
2013
2031
2103
2130
2301
2310
3012
3021
3102
3120
3201
3210

Which is what I wanted. But this code does not look so good. I have to copy the slice multiple times before I remove an item, and then loop through the items on that slice. Is there a better and more dry way for me to achieve what I am doing here? I am going to the same thing for a slice that looks like this: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

I don't think writing each loop like I have done 10 times is a good way of doing things. Any suggestions how I can do this?

答案1

得分: 5

你似乎不知道你正在做的事情被称为“生成排列”。否则,通过谷歌搜索一个高效的算法来完成这个任务将会很容易。

英文:

You don't seem to know that what you are doing is called generating permutations. Otherwise it would be easy to google an efficient algorithm for doing it.

huangapple
  • 本文由 发表于 2016年10月13日 04:37:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/40007920.html
匿名

发表评论

匿名网友

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

确定