Given a square matrix, calculate the absolute difference between the sums of its diagonals.

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix is shown below: 1 2 3 4 5 6 9 8 9 The left-to-right diagonal = 1+5+9=15. The right to left diagonal = 3+5+9=17. Their absolute difference is |15-17| = 2.

/* Complete the 'diagonalDifference' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY arr as parameter.
 */

function diagonalDifference($arr) {
    // Write your code here
   
    $sum1=0;
    $sum2=0;
     $count=count($arr)-1;
         //return $count;
    for($i=0;$i < count($arr);$i++)
    {
        for($j=0;$j <count($arr);$j++)
        {
            if($i == $j)
            {
                $sum1+=$arr[$i][$j];
             
           
            }
            if($j==$count)
            {
                $sum2+=$arr[$i][$j];

                $count--;

            }

        }
        
    }
    
return abs($sum1-$sum2);
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$arr = array();

for ($i = 0; $i < $n; $i++) {
    $arr_temp = rtrim(fgets(STDIN));

    $arr[] = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY));
}

$result = diagonalDifference($arr);

fwrite($fptr, $result . "\n");

fclose($fptr);
                         
    

0 Response to "Given a square matrix, calculate the absolute difference between the sums of its diagonals. "

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel