简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM