This HackerRank challenge took some thinking. I needed to be able to accept a variable size multidimensional array, add the diagonals, and then find the absolute value of their difference. I haven’t needed to work with multidimensional arrays much in the past, so it took some working through the algorithm to ensure I was incrementing my values in the correct spots.

These challenges are great mental floss for coding while I learn Java.

import java.io.*; import java.util.*; import java.lang.Math; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner in = new Scanner(System.in); //get the value that defines the size of the input matrix int n = in.nextInt(); int[][] numberArray = new int[n][n]; String input = in.nextLine();; int currentDiagnalPosition1 = 0, currentDiagnalPosition2 = n-1; int runningTotal1 = 0, runningTotal2 = 0; for(int j = 0; j < n; j++) { input = in.nextLine(); for(int k = 0; k < n; k++) { String[] data = input.trim().split("\\s+"); numberArray[j][k] = Integer.parseInt(data[k]); if(currentDiagnalPosition1 == k) { runningTotal1 = runningTotal1 + numberArray[j][k]; } if(currentDiagnalPosition2 == k) { runningTotal2 = runningTotal2 + numberArray[j][k]; } } currentDiagnalPosition1 = currentDiagnalPosition1 + 1; currentDiagnalPosition2 = currentDiagnalPosition2 - 1; } System.out.println(Math.abs(runningTotal1-runningTotal2)); } }