Home > OS >  Using Modulo instead of two loops
Using Modulo instead of two loops

Time:03-09

I'm new at programming in general and learning C# right now.

I just wrote a little programm where I have to step through an int[] in a specific pattern. The pattern is as follows:

  • Start at the last entry of the array (int i)
  • form the sum of i and (if avaible) the three entrys above (e.g. i = i-1 ... i = i-3)
  • Change i to i -= 4 (if avaible)
  • Repeat from step 2 until i = 0;

Therefore i wrote the following loop:

        for (int i = intArray.Length - 1; i >= 0; i -= 4)
        {
            for (int a = 1; a <= 3; a  )
            {
                if (i - a >= 0)
                {
                    intArray[i]  = intArray[i - a];
                    intArray[i - a] = 0;
                }
            }
        }

Now my new assignment is to change my code to only use 1 loop with the help of modulo-operations. I do understand what modulo does, but i can't figure out how to use it to get rid of the second loop.

Maybe somebody explain it to me? Thank you very much in advance.

CodePudding user response:

iterating the array reversely makes it a bit more complicated, but what you wanted to get rid of inner loop with modulo is probably this:

        var intArray = Enumerable.Range(1, 15).ToArray();

        for (int i = 1; i < intArray.Length - 1;  i   )
        {
            intArray[i - (i % 4)]  = intArray[i];
            intArray[i] = 0;
        }

CodePudding user response:

While iterating over the array, the idea would be to use the modulo 4 operation to calculate the next index to which you will add the current value.

This should work with any array lengths:

        for (int i = 0; i < intArray.Length; i  ){
            // we check how far away we are from next index which stores the sum
            var offset = (intArray.Length - 1 - i) % 4;
            if (offset == 0) continue;
            intArray[i offset]  = intArray[i];
            intArray[i] = 0;
        }
  • Related