Created
August 9, 2018 13:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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