diagonal difference javascript

Diagonal difference is a concept in programming where you can find the difference between two diagonals in a two dimensional array. In JavaScript, this can be achieved by using a nested loop.


    function diagonalDifference(arr) {
        let diag1 = 0; 
        let diag2 = 0;

        // Iterate through the array starting at 0,0
        for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < arr.length; j++) {
                // Check if i & j are the same
                if (i === j) {
                    diag1 += arr[i][j];
                }
                // Check if i+j is equal to the length of the array
                if (i + j === arr.length - 1) {
                    diag2 += arr[i][j];
                }
            }
        }

        // Return the absolute difference between the two diagonals
        return Math.abs(diag1 - diag2);
    }
    

This code takes a two dimensional array as an argument and iterates through the array using two nested loops. The inner loop checks if the current indices (i & j) are equal (i.e. the current element is on the main diagonal), and if so, adds the value to the variable diag1. The second check is if the sum of the two indices is equal to the length of the array (i.e. the current element is on the opposite diagonal), and if so, adds the value to the variable diag2. After the nested loop has completed, the absolute difference between the two diagonals is returned.

This solution will work for any size array, and is fairly simple to understand. It does, however, have a time complexity of O(n2) due to the nested loop, so for larger arrays it may not be the most efficient solution.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe