3 * This file is part of the Diff package.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace SebastianBergmann\Diff\LCS;
14 * Memory-efficient implementation of longest common subsequence calculation.
16 class MemoryEfficientImplementation implements LongestCommonSubsequence
19 * Calculates the longest common subsequence of two arrays.
26 public function calculate(array $from, array $to)
28 $cFrom = count($from);
33 } elseif ($cFrom == 1) {
34 if (in_array($from[0], $to)) {
35 return array($from[0]);
40 $i = intval($cFrom / 2);
41 $fromStart = array_slice($from, 0, $i);
42 $fromEnd = array_slice($from, $i);
43 $llB = $this->length($fromStart, $to);
44 $llE = $this->length(array_reverse($fromEnd), array_reverse($to));
48 for ($j = 0; $j <= $cTo; $j++) {
49 $m = $llB[$j] + $llE[$cTo - $j];
57 $toStart = array_slice($to, 0, $jMax);
58 $toEnd = array_slice($to, $jMax);
61 $this->calculate($fromStart, $toStart),
62 $this->calculate($fromEnd, $toEnd)
73 private function length(array $from, array $to)
75 $current = array_fill(0, count($to) + 1, 0);
76 $cFrom = count($from);
79 for ($i = 0; $i < $cFrom; $i++) {
82 for ($j = 0; $j < $cTo; $j++) {
83 if ($from[$i] == $to[$j]) {
84 $current[$j + 1] = $prev[$j] + 1;
86 $current[$j + 1] = max($current[$j], $prev[$j + 1]);