diagonalDifference

    0

    0

    This function calculates the difference between two arrays. It first calculates the length of the arrays and assigns each element of the first array to a variable. It then proceeds to do a for loop which compares each element in the first array with the corresponding element in the second array. If the two arrays have the same elements, the variable d1 is incremented and the for loop terminates. If the elements in the first array and the second array are not equal, the variable d2 is incremented. The difference between these two variables is then calculated and returned.

    function diagonalDifference(arr) {
        var n = arr.length; 
        var d1 = 0;
        var d2 = 0;
      for(var i=0; i<n; i++){
          for(var j=0; j<n; j++){
      
              if(i === j) {
                d1 += arr[i][j];
              }
      
              if(i + j === n - 1){
                d2 += arr[i][j];
              }
          }
      }
      return Math.abs(d1 - d2);
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.