如何根据n值制作循环?

假设我的 n 值为 3,


代码将如下所示:


//Loop 1

for i := 0; i < len(x); i++ {

        //Loop 2

        for j := 0; (j < len(x)) && (j != i); j++ {

            //Loop 3

            for k := 0; (k < len(x)) && (k != i) && (k != j); k++ {

            }

        }

    }

但是,我试图弄清楚如何根据值自动生成它,以便当 n 值为 5 时,它应该生成:


Loop 1 {

   Loop 2 {

      Loop 3 {

         Loop 4 {

            Loop 5 {

            }

         }

      }

   }

}

可能吗?


慕码人2483693
浏览 88回答 1
1回答

慕哥9229398

这是一个递归示例https://go.dev/play/p/cLm-QHydM37这导致以下迭代当长度为 5 时:map[1:5 2:25 3:125 4:625 5:3125]当长度为 3 时:map[1:3 2:9 3:27 4:0 5:0]package mainimport "fmt"func main() {&nbsp; &nbsp; count := map[int]int{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}&nbsp; &nbsp; // This recursion is based on https://gobyexample.com/recursion&nbsp; &nbsp; var loopFunc func(current int, data []string)&nbsp; &nbsp; loopFunc = func(current int, data []string) {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; (i < len(data)) && (len(data) != current-1); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count[current] = count[current] + 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loopFunc(current+1, data)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; loopFunc(1, make([]string, 5))&nbsp; &nbsp; fmt.Println(count)}我可能没有完全正确的循环逻辑,但这应该是您继续前进的跳板。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go