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 * Time-efficient implementation of longest common subsequence calculation.
16 class TimeEfficientImplementation implements LongestCommonSubsequence
19 * Calculates the longest common subsequence of two arrays.
26 public function calculate(array $from, array $to)
29 $fromLength = \count($from);
30 $toLength = \count($to);
31 $width = $fromLength + 1;
32 $matrix = new \SplFixedArray($width * ($toLength + 1));
34 for ($i = 0; $i <= $fromLength; ++$i) {
38 for ($j = 0; $j <= $toLength; ++$j) {
39 $matrix[$j * $width] = 0;
42 for ($i = 1; $i <= $fromLength; ++$i) {
43 for ($j = 1; $j <= $toLength; ++$j) {
44 $o = ($j * $width) + $i;
48 $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
56 while ($i > 0 && $j > 0) {
57 if ($from[$i - 1] === $to[$j - 1]) {
58 $common[] = $from[$i - 1];
62 $o = ($j * $width) + $i;
64 if ($matrix[$o - $width] > $matrix[$o - 1]) {
72 return \array_reverse($common);