Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/MatchesSolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ protected function newIndex(array $matrix, int $i, int $j)
{
return new Match(
[
$i - $matrix[$i][$j] + 1,
$j - $matrix[$i][$j] + 1,
$i - $matrix[$i%2][$j] + 1,
$j - $matrix[$i%2][$j] + 1,
],
$matrix[$i][$j]
$matrix[$i%2][$j]
);
}

Expand Down
16 changes: 8 additions & 8 deletions src/Solver.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Solver implements SolverInterface
*/
protected function newIndex(array $matrix, int $i, int $j)
{
return $i - $matrix[$i][$j] + 1;
return $i - $matrix[$i%2][$j] + 1;
}

/**
Expand Down Expand Up @@ -58,28 +58,28 @@ public function solve(string $stringA, string $stringB)
$charsA = str_split($stringA);
$charsB = str_split($stringB);

$matrix = array_fill_keys(array_keys($charsA), array_fill_keys(array_keys($charsB), 0));
$matrix = array_fill_keys([0, 1], array_fill_keys(array_keys($charsB), 0));
$longestLength = 0;
$longestIndexes = [];

foreach ($charsA as $i => $charA) {
foreach ($charsB as $j => $charB) {
if ($charA === $charB) {
if (0 === $i || 0 === $j) {
$matrix[$i][$j] = 1;
$matrix[$i%2][$j] = 1;
} else {
$matrix[$i][$j] = $matrix[$i - 1][$j - 1] + 1;
$matrix[$i%2][$j] = $matrix[($i-1)%2][$j - 1] + 1;
}

$newIndex = $this->newIndex($matrix, $i, $j);
if ($matrix[$i][$j] > $longestLength) {
$longestLength = $matrix[$i][$j];
if ($matrix[$i%2][$j] > $longestLength) {
$longestLength = $matrix[$i%2][$j];
$longestIndexes = [$newIndex];
} elseif ($matrix[$i][$j] === $longestLength) {
} elseif ($matrix[$i%2][$j] === $longestLength) {
$longestIndexes[] = $newIndex;
}
} else {
$matrix[$i][$j] = 0;
$matrix[$i%2][$j] = 0;
}
}
}
Expand Down