1 <?php declare(strict_types=1);
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.
10 namespace SebastianBergmann\Diff;
12 use function array_fill;
13 use function array_merge;
14 use function array_reverse;
15 use function array_slice;
17 use function in_array;
20 final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
25 public function calculate(array $from, array $to): array
27 $cFrom = count($from);
35 if (in_array($from[0], $to, true)) {
42 $i = (int) ($cFrom / 2);
43 $fromStart = array_slice($from, 0, $i);
44 $fromEnd = array_slice($from, $i);
45 $llB = $this->length($fromStart, $to);
46 $llE = $this->length(array_reverse($fromEnd), array_reverse($to));
50 for ($j = 0; $j <= $cTo; $j++) {
51 $m = $llB[$j] + $llE[$cTo - $j];
59 $toStart = array_slice($to, 0, $jMax);
60 $toEnd = array_slice($to, $jMax);
63 $this->calculate($fromStart, $toStart),
64 $this->calculate($fromEnd, $toEnd)
68 private function length(array $from, array $to): array
70 $current = array_fill(0, count($to) + 1, 0);
71 $cFrom = count($from);
74 for ($i = 0; $i < $cFrom; $i++) {
77 for ($j = 0; $j < $cTo; $j++) {
78 if ($from[$i] === $to[$j]) {
79 $current[$j + 1] = $prev[$j] + 1;
81 // don't use max() to avoid function call overhead
82 if ($current[$j] > $prev[$j + 1]) {
83 $current[$j + 1] = $current[$j];
85 $current[$j + 1] = $prev[$j + 1];