HackerRank Problem Solving - A Very Big Sum
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix arr
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
.
Function description
Complete the diagonalDifference
function in the editor below.
diagonalDifference takes the following parameter:
- int arr[n][m]: an array of integers
Return
- int: the absolute diagonal difference
Solution in PHP:
<?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
$firstSum = 0;
$secondSum = 0;
$n = count($arr);
for ($i = 0; $i < $n; $i++) {
$firstSum += $arr[$i][$i];
$secondSum += $arr[$i][$n - 1 - $i];
}
return abs($firstSum - $secondSum);
}
$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);