Last active
August 11, 2021 01:03
-
-
Save elishaukpong/5653bb6f219a57e962c942f8c1fdbbd5 to your computer and use it in GitHub Desktop.
Problem: Given a square matrix, calculate the absolute difference between the sums of its diagonals. Link: https://www.hackerrank.com/challenges/diagonal-difference/problem
This file contains 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
function diagonalDifference($arr) { | |
//initialize a new array to hold the diagonals, left and right | |
$rightD = []; | |
$leftD = []; | |
//iterate through the parent array, taking note of it's key | |
foreach($arr as $key => $lineArray) | |
{ | |
//iterate through the diagonal lines, take note of the keys | |
foreach ($lineArray as $innerKey => $value){ | |
//if the parent key is equal to inner key, then we have a member of the right diagonal | |
//e.g $a[0][0], $a[1][1]...$a[n][m] | |
if($key == $innerKey){ | |
$rightD[] = $value; | |
} | |
//we are picking values from the end of the array, in steps of one | |
//if the inner key is equal to the arrayCount - the inner key, then we have a member of the left diagonal | |
//e.g $a[0][count-0], $a[1][count - 1]...$a[n][count - m] | |
if($innerKey == ((count($arr) - 1) - $key)){ | |
$leftD[] = $value; | |
} | |
} | |
} | |
return abs(array_sum($rightD) - array_sum($leftD)); | |
} | |
//e.g | |
var_dump(diagonalDifference([[11,2,4],[4,5,6],[10,8,-12]])); | |
//output 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment