Skip to content

Instantly share code, notes, and snippets.

@krabello
Created October 15, 2017 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krabello/72ea13440b27c3e1c5a4b695c6b6b32c to your computer and use it in GitHub Desktop.
Save krabello/72ea13440b27c3e1c5a4b695c6b6b32c to your computer and use it in GitHub Desktop.
Count Negative Integers in Row/Column-Wise Sorted Matrix
function countNegatives($matrix) {
if (!is_array($matrix)) {
throw new TypeError('The matrix is not an array');
}
//rows
$rows = count($matrix);
// columns
$columns = (array_sum(array_map('count', $matrix)) / $rows);
$count = 0;
$i = 0;
$j = $columns - 1;
$sortedMatrix = [];
foreach ($matrix as $row) {
sort($row, SORT_NUMERIC);
$sortedMatrix[] = $row;
}
while (($j >= 0) && ($i < $rows)) {
if ($sortedMatrix[$i][$j] < 0) {
$count += $j +1;
$i++;
} else {
$j--;
}
}
return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment