3 * This file is part of sebastian/diff.
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);
36 if (\in_array($from[0], $to, true)) {
37 return array($from[0]);
43 $i = (int) ($cFrom / 2);
44 $fromStart = \array_slice($from, 0, $i);
45 $fromEnd = \array_slice($from, $i);
46 $llB = $this->length($fromStart, $to);
47 $llE = $this->length(\array_reverse($fromEnd), \array_reverse($to));
51 for ($j = 0; $j <= $cTo; $j++) {
52 $m = $llB[$j] + $llE[$cTo - $j];
60 $toStart = \array_slice($to, 0, $jMax);
61 $toEnd = \array_slice($to, $jMax);
64 $this->calculate($fromStart, $toStart),
65 $this->calculate($fromEnd, $toEnd)
75 private function length(array $from, array $to)
77 $current = \array_fill(0, \count($to) + 1, 0);
78 $cFrom = \count($from);
81 for ($i = 0; $i < $cFrom; $i++) {
84 for ($j = 0; $j < $cTo; $j++) {
85 if ($from[$i] === $to[$j]) {
86 $current[$j + 1] = $prev[$j] + 1;
88 $current[$j + 1] = \max($current[$j], $prev[$j + 1]);