如何根据n的值创建循环?

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

How to make loop based on n value?

问题

假设我有一个值 n 等于 3,

代码看起来像这样:

//循环 1
for i := 0; i < len(x); i++ {
        //循环 2
		for j := 0; (j < len(x)) && (j != i); j++ {
            //循环 3
			for k := 0; (k < len(x)) && (k != i) && (k != j); k++ {
			}
		}
	}

然而,我正在尝试弄清楚如何根据值自动生成代码,所以当 n 的值为 5 时,它应该生成:

循环 1 {
   循环 2 {
      循环 3 {
         循环 4 {
            循环 5 {
            }
         }
      }
   }
}

这可能吗?

英文:

Let say i have n value 3,

The code will look like this :

//Loop 1
for i := 0; i &lt; len(x); i++ {
        //Loop 2
		for j := 0; (j &lt; len(x)) &amp;&amp; (j != i); j++ {
            //Loop 3
			for k := 0; (k &lt; len(x)) &amp;&amp; (k != i) &amp;&amp; (k != j); k++ {
			}
		}
	}

However, I was trying to figure out how to make it automatically based on the value, so that when the n value is 5, it should generate:

Loop 1 {
   Loop 2 {
      Loop 3 {
         Loop 4 {
            Loop 5 {
            }
         }
      }
   }
}

Is it possible?

答案1

得分: 1

这是一个递归的示例: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 main

import "fmt"

func main() {
    count := map[int]int{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

    // 这个递归基于 https://gobyexample.com/recursion
    var loopFunc func(current int, data []string)
    loopFunc = func(current int, data []string) {
        for i := 0; (i < len(data)) && (len(data) != current-1); i++ {
            count[current] = count[current] + 1
            loopFunc(current+1, data)
        }
    }

    loopFunc(1, make([]string, 5))
    fmt.Println(count)
}

我可能没有完全理解你的循环逻辑,但这应该可以为你提供一个起点,供你继续进行。

英文:

Here is an example of a recursion https://go.dev/play/p/cLm-QHydM37

This results in the following iterations

When length is 5: map[1:5 2:25 3:125 4:625 5:3125]

When length is 3: map[1:3 2:9 3:27 4:0 5:0]

package main

import &quot;fmt&quot;

func main() {
	count := map[int]int{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

	// This recursion is based on https://gobyexample.com/recursion
	var loopFunc func(current int, data []string)
	loopFunc = func(current int, data []string) {
		for i := 0; (i &lt; len(data)) &amp;&amp; (len(data) != current-1); i++ {
			count[current] = count[current] + 1
			loopFunc(current+1, data)
		}
	}

	loopFunc(1, make([]string, 5))
	fmt.Println(count)
}

I might not have your loop logic exactly right but this should be a springboard for you to continue on from.

huangapple
  • 本文由 发表于 2022年2月9日 12:27:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/71044009.html
匿名

发表评论

匿名网友

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

确定