Calculate the diagonal difference of an N x N matrix

<?php
/**
* Calculate the diagonal difference of an N x N matrix
* 
* runs in O(n)
*
* @param int   $n size of N x N array
* @param array $a N x N array
*
* @return number
*/
function diagonalDifference($n = 0, $a = array()){
    $first_d = 0;
    $second_d = 0;
    for($i = 0, $j = $n - 1; $i < $n; $i++, $j--){
        $first_d += $a[$i][$i];
        $second_d += $a[$j][$i];
    }
   return abs($first_d - $second_d);
}
This entry was posted in algorithms and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *