Skip to content

Instantly share code, notes, and snippets.

@tanmay27vats
Created August 9, 2018 13:29
Show Gist options
  • Save tanmay27vats/ca410c46d5c0210cf1d940bf9cf8aeaa to your computer and use it in GitHub Desktop.
Save tanmay27vats/ca410c46d5c0210cf1d940bf9cf8aeaa to your computer and use it in GitHub Desktop.
Diagonal difference of 2D array - PHP. Given a square matrix, calculate the absolute difference between the sums of its diagonals... Note: |x| is the absolute value of x
// Complete the diagonalDifference function below.
function diagonalDifference($arr) {
$d_ar = [];
$main_len = count($arr);
foreach($arr as $key => $ar) {
$sub_len = count($ar);
if($main_len != $sub_len) {
throw new Exception('Array index count mismatched. Hence this is not square array.');
}
$d_ar[0][] = $ar[$key];
$d_ar[1][] = $ar[($main_len-$key-1)];
}
return abs((array_sum($d_ar[0]) - array_sum($d_ar[1])));
}
$arr = [
[1,2,3],
[4,5,6],
[9,8,9]
];
$result = diagonalDifference($arr);
echo $result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment