Home > Blockchain >  How to make loop based on n value?
How to make loop based on n value?

Time:02-10

Let say i have n value 3,

The code will look like this :

//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   {
            }
        }
    }

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?

CodePudding user response:

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 "fmt"

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 < len(data)) && (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.

  • Related