Skip to content

Instantly share code, notes, and snippets.

@jkintscher
Created February 13, 2012 15:58
Show Gist options
  • Select an option

  • Save jkintscher/1817835 to your computer and use it in GitHub Desktop.

Select an option

Save jkintscher/1817835 to your computer and use it in GitHub Desktop.
Find existing saddle points in any given 2-dimensional matrix
<?php
function find_saddle_points($arr) {
$points = array();
// traverse the passed matrix by row
foreach($arr as $i => $row) {
// get the highest value from each row
$max = max($row);
foreach($row as $j => $cell) {
// for each highest value only, check whether it is the lowest value in its column
if($cell == $max AND min_in_col($arr, $cell, $j)) {
$points[] = array($i, $j);
}
}
}
print_r($points ? $points : 'No saddle points found.');
}
function min_in_col($arr, $val, $col) {
foreach($arr as $row) {
// as soon as there is at least one lower value, quit
if($val > $row[$col]) {
return FALSE;
}
}
return TRUE;
}
<?php
include('saddle.php');
$arr1 = array(
array(39, 43, 49, 29, 18),
array(30, 47, 24, 29, 15),
array(49, 50, 39, 20, 33),
array(18, 38, 35, 32, 35),
array(29, 44, 18, 34, 44)
);
find_saddle_points($arr1);
// Output: Array ( [0] => Array ( [0] => 3 [1] => 1 ) )
$arr2 = array(
array(50, 27, 36, 43, 39),
array(36, 14, 35, 40, 19),
array(20, 33, 48, 32, 40),
array(41, 40, 15, 22, 19),
array(21, 24, 24, 31, 18)
);
find_saddle_points($arr2);
// Output: No saddle points found.
$arr3 = array(
array(39, 43, 49, 29, 18),
array(30, 47, 24, 29, 15),
array(49, 50, 39, 20, 33),
array(18, 38, 35, 32, 38),
array(29, 44, 18, 34, 44)
);
find_saddle_points($arr3);
// Output: Array ( [0] => Array ( [0] => 3 [1] => 1 ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment