2

I was wondering if I could write this very thing but with one single loop, instead of two?

for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[0].length; col++) {
            if ((row + col) % 2 == 0) {
                System.out.print(matrix[row][col] + ", ");

                sum += matrix[row][col];
            }
        }

        System.out.println("with a sum of " + sum);
    }

Actually just ignore the body of the loop.. It's totally irrelevant, I have no idea whatsoever why I included it.. How to somehow combine the two for loops is my question.

Just keep it simple, if possible. Thank you!

2 Answers 2

7

You can, though it's inefficient:

for(int i = 0 ; i < matrix.length * matrix[0].length ; i++)
     sum += matrix[i % matrix.length][i / matrix.length];

The basic idea would be to map each index to a value in a 2d-number space, using the fact that we know the length of each "row" of the array (matrix.length). We can compose a single index, that uniquely identifies two indices matrix[x][y], by z = x + y * matrix.length. The reverse of this would then be:

x = z % matrix.length
y = z / matrix.length

This depiction would be complete, e.g. each z in [0 , matrix.length * matrix[0].length) would identify exactly one pair of indices, thus we can use it here.

Sign up to request clarification or add additional context in comments.

Comments

1

Paul's answer is initially how I thought to do it. But there is the slight restriction that you need to have a rectangular two-dimensional array (i.e. the sub-arrays are all the same length). If you're modelling a "matrix", this is likely to be the case, but more generally you may want to sum up non-rectangular arrays.

A way around this is to do something like this:

for (int r = 0, c = 0; r < matrix.length;) {
  if (c < matrix[r].length) {
    sum += matrix[r][c];
    ++c;
  } else {
    c = 0;
    ++r;
  }
}

Although it's getting a bit messy. I'd just go for a nested loop instead.

Comments

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.