From 0248a96e72699a42a0e56c9b0a2bef1b5d050faf Mon Sep 17 00:00:00 2001 From: Seb35 Date: Sat, 27 Oct 2018 17:51:50 +0200 Subject: [PATCH] Memory optimisation Only the current and the previous rows are needed. This trick is a great improvement for long texts: it reduces space from O(mn) to O(n). (It could be still slightly improved to O(min(m,n)) by swapping the two texts.) --- src/MatchesSolver.php | 6 +++--- src/Solver.php | 16 ++++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/MatchesSolver.php b/src/MatchesSolver.php index 5079be1..7bf12f7 100644 --- a/src/MatchesSolver.php +++ b/src/MatchesSolver.php @@ -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] ); } diff --git a/src/Solver.php b/src/Solver.php index 74ee735..ae6f36d 100644 --- a/src/Solver.php +++ b/src/Solver.php @@ -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; } /** @@ -58,7 +58,7 @@ 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 = []; @@ -66,20 +66,20 @@ public function solve(string $stringA, string $stringB) 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; } } }