Search code examples
c#loopsnestednested-loops

How would you create n nested loops for math?


So, I am trying to wrap my head around understanding how you can use a variable to denote how many times a loop is nested.

Here is an example I write up to simulate the output of dimensions = 4:

static void Main(string[] args)
    {

        int dimensions = 4;    // e.g. for (1, 2, 3, 4), dimensions = 4

        Console.WriteLine($"{addNumbers(dimensions)}");

        Console.ReadKey();
    }

    static long addNumbers(int dimensions)
    {
        long number = 0;

        // hard coded to be dimensions = 4
        for (int h = 0; h <= dimensions; h++)
            for (int i = 0; i <= dimensions; i++)
                for (int j = 0; j <= dimensions; j++)
                    for (int k = 0; k <= dimensions; k++)
                        number += h + i + j + k;    // just some random math

        return number;
    }

This will present the expected output of:

5000

So to readdress the problem, how can I code to allow this for n dimensions? Thanks for your help!


Solution

  • For arbitrary n dimensions you can loop with a help of array int[] address which represents n dimensions:

      static long addNumbers(int dimensions) {
        int[] address = new int[dimensions];
    
        // size of each dimension; not necessary equals to dimensions
        // + 1 : in your code, int the loops you have i <= dimensions, j <= dimensions etc.
        int size = dimensions + 1;
    
        long number = 0;
    
        do {
          //TODO: some math here
          //      i == address[0]; j = address[1]; ... etc.
          number += address.Sum(); 
    
          // next address: adding 1 to array
          for (int i = 0; i < address.Length; ++i) {
            if (address[i] >= size - 1)
              address[i] = 0;
            else {
              address[i] += 1;
              break; 
            }
          }
        }  
        while (!address.All(index => index == 0)); // all 0 address - items're exhausted
    
        return number; 
      }  
    

    Finally, let's add some Linq to look at the results:

      int upTo = 5;
    
      string report = string.Join(Environment.NewLine, Enumerable
        .Range(1, upTo)
        .Select(i => $"{i} -> {addNumbers(i),6}"));
    
      Console.Write(report); 
    

    Outcome:

    1 ->      1 
    2 ->     18
    3 ->    288
    4 ->   5000 // <- We've got it: 5000 for 4 dimensions
    5 ->  97200