Skip to content
the poor coder

diagonal difference javascript

Poor Man
Published
Reading time
1 min read

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.

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC