Find the difference of diagonal sum in matrice i.e.,
[1 2 3]
[4 5 6]
[7 8 9]
First diagonal is [1 5 9] and second diagonal is [3 5 7] i.e., 1st diagonal sum is 1+5+9 =15 and second diagonal sum is 3+5+7 = 15 so, difference is 0. If it is negative number it should be converted to positive.
<?php
/*
* 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
$n=count($arr);
$firstD =0;
$secondD=0;
for($i=0;$i<$n;$i++){
$firstD+=$arr[$i][$i];
$secondD+=$arr[$n-$i-1][$i];
}
return abs($firstD - $secondD);
}
$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);
No comments:
Post a Comment