0

How can I write recursive function for this for loops I am making sum of this array elements.

        int[,,,] exampleArray = new int[1,2,3,4];
        int sum = 0;
        for (int i = 0; i < 1; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                    for (int l = 0; l < 4; l++)
                    {
                        sum += exampleArray[i, j, k, l];
                    }
                }
            }
        }
        Console.WriteLine(sum);
2
  • 1
    Is this a course question? Seems a very hard one to me. I can't think of a way to write that recursively without increasing the complexity significantly. Commented Oct 8, 2022 at 18:14
  • 1
    A problem that a data structures teacher at university asked us about Commented Oct 8, 2022 at 18:24

1 Answer 1

2

it is actually quite simple, just need a way to represent all 4 indexes as single variable:

static int recursiveSum(int[,,,] a, int index = 0)
{
    int ti = index;
    int l = ti % a.GetLength(3); ti /= a.GetLength(3);
    int k = ti % a.GetLength(2); ti /= a.GetLength(2);
    int j = ti % a.GetLength(1); ti /= a.GetLength(1);
    int i = ti % a.GetLength(0); ti /= a.GetLength(0);

    if (ti > 0) {
        return 0;
    }

    return a[i, j, k, l] + recursiveSum(a, index + 1);
}

static void Main(string[] args)
{
    int[,,,] exampleArray = new int[1, 2, 3, 4];
    int sum = recursiveSum(exampleArray);
    Console.WriteLine(sum);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@FurkanŞen start with array where all dimensions are 10, you will notice that indexes will go like 0000, 0001, 0002... ie the normal decimal numbers, then just change base of each digit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.