dougui4325 2016-10-12 20:37
浏览 100
已采纳

进行切片和循环:遍历切片器项目,同时在每个循环中减少每个项目1个

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条回答 默认 最新

  • doufei2007 2016-10-12 20:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器