Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active June 7, 2019 02:11
Show Gist options
  • Select an option

  • Save anushshukla/db825638cf55245393117284f8ddfa57 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/db825638cf55245393117284f8ddfa57 to your computer and use it in GitHub Desktop.
Get Distinct Elements Common To All Rows of n x n Matrix having unique values
<?php
function getDistinctElementsCommonToAllRows($matrix) {
$matches = '';
$matrixLength = count($matrix);
$matrixLastIndex = $matrixLength - 1;
$matrixPivotIndex = round($matrixLastIndex / 2);
for ($i=0; $i < $matrixPivotIndex; $i++) {
$row = $matrix[$i];
$anotherRow = $matrix[$matrixLastIndex - $i];
$currentRowMatch = '';
// @todo improve complexity by refactoring below 2 nested loops
foreach ($row as $key => $rowValue) {
foreach ($anotherRow as $key => $anotherRowValue) {
// var_dump("$rowValue === $anotherRowValue => " . ($isMatching ? 'true' : 'false'));
$isMatching = $rowValue === $anotherRowValue;
if ($isMatching) {
if ($currentRowMatch) $currentRowMatch .= ' ';
$currentRowMatch .= $rowValue;
}
}
}
if (!$currentRowMatch) break;
if ($matches && $matches !== $currentRowMatch) break;
$matches = $currentRowMatch;
}
return $matches ?: 'No match found';
};
$sampleMatrix = [
[2, 1, 4, 3],
[1, 2, 3, 2],
[3, 6, 2, 3],
[5, 2, 5, 3]
];
// echo getDistinctElementsCommonToAllRows($sampleMatrix);
// Output: 2 3
$sampleMatrix2 = [
[12, 1, 14, 3, 16],
[14, 2, 1, 3, 35],
[14, 1, 14, 3, 11],
[14, 25, 3, 2, 1],
[1, 18, 3, 21, 14]
];
echo getDistinctElementsCommonToAllRows($sampleMatrix2);
// Output: 1 3 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment