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_reverse;
17 final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
22 public function calculate(array $from, array $to): array
25 $fromLength = count($from);
26 $toLength = count($to);
27 $width = $fromLength + 1;
28 $matrix = new SplFixedArray($width * ($toLength + 1));
30 for ($i = 0; $i <= $fromLength; $i++) {
34 for ($j = 0; $j <= $toLength; $j++) {
35 $matrix[$j * $width] = 0;
38 for ($i = 1; $i <= $fromLength; $i++) {
39 for ($j = 1; $j <= $toLength; $j++) {
40 $o = ($j * $width) + $i;
44 $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
52 while ($i > 0 && $j > 0) {
53 if ($from[$i - 1] === $to[$j - 1]) {
54 $common[] = $from[$i - 1];
58 $o = ($j * $width) + $i;
60 if ($matrix[$o - $width] > $matrix[$o - 1]) {
68 return array_reverse($common);