Find sum of top-left to bottom-right diagonals in Java

The challenge

Given a square matrix (i.e. an array of subarrays), find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on…

Examples

array = [[1, 2],
         [3, 4]]

diagonal sum: 1 + 4 = 5
array = [[5, 9, 1, 0],
         [8, 7, 2, 3],
         [1, 4, 1, 9],
         [2, 3, 8, 2]]

diagonal sum: 5 + 7 + 1 + 2 = 15

The solution in Java code

Option 1:

public class Diagonal {
  public static int diagonalSum(final int[][] matrix) {
    int count = 0;
    for(int i=0; i<matrix.length; i++) {
      count += matrix[i][i];
    }
    return count;
  }
}

Option 2:

import java.util.stream.IntStream;

public class Diagonal {
  public static int diagonalSum(final int[][] matrix) {
    return IntStream.range(0, matrix.length).map(i -> matrix[i][i]).sum();
  }
}

Option 3:

public class Diagonal {
  public static int diagonalSum(final int[][] matrix) {
    return java.util.stream.IntStream.range(0, matrix.length)
        .map(i -> matrix[i][i])
        .sum();
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {

    @Test
    public void testMatrix1() {
       final int[][] matrix = new int[][]{{12}};
       assertEquals(12, Diagonal.diagonalSum(matrix));
    }
    
    @Test
    public void testMatrix2() {
      final int[][] matrix = new int[][]{{1, 2}, {3, 4}};
      assertEquals(5, Diagonal.diagonalSum(matrix));
    }
    
    @Test
    public void testMatrix3() {
      final int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
      assertEquals(15, Diagonal.diagonalSum(matrix));
    }
    
    @Test
    public void testMatrix4() {
      final int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
      assertEquals(34, Diagonal.diagonalSum(matrix));
    }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments