gpt4 book ai didi

Go slice 和循环 : Multilple loop through slice items while reducing the items with 1 each on each loop

转载 作者:IT王子 更新时间:2023-10-29 01:26:46 25 4
gpt4 key购买 nike

我有一个整数片段,我想循环多次,但每次我做另一个循环时,我都想从父循环中排除该项目。

像这样:

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

这就是我想要的。但是这段代码看起来不太好。在删除项目之前,我必须多次复制 slice ,然后循环遍历该 slice 上的项目。有没有更好更干的方式让我实现我在这里做的事情?我将对如下所示的 slice 执行相同的操作:[]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

我不认为像我已经写过 10 次那样编写每个循环是一种好的做事方式。有什么建议吗?

最佳答案

你似乎不知道你正在做的事情叫做生成排列。否则,很容易通过谷歌搜索到一个有效的算法。

关于Go slice 和循环 : Multilple loop through slice items while reducing the items with 1 each on each loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com