Last active
June 7, 2019 02:11
-
-
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
This file contains hidden or 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
| <?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