Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace SebastianBergmann\Diff\LCS; Chris@0: Chris@0: /** Chris@0: * Time-efficient implementation of longest common subsequence calculation. Chris@0: */ Chris@0: class TimeEfficientImplementation implements LongestCommonSubsequence Chris@0: { Chris@0: /** Chris@0: * Calculates the longest common subsequence of two arrays. Chris@0: * Chris@0: * @param array $from Chris@0: * @param array $to Chris@0: * Chris@0: * @return array Chris@0: */ Chris@0: public function calculate(array $from, array $to) Chris@0: { Chris@0: $common = array(); Chris@12: $fromLength = \count($from); Chris@12: $toLength = \count($to); Chris@0: $width = $fromLength + 1; Chris@0: $matrix = new \SplFixedArray($width * ($toLength + 1)); Chris@0: Chris@0: for ($i = 0; $i <= $fromLength; ++$i) { Chris@0: $matrix[$i] = 0; Chris@0: } Chris@0: Chris@0: for ($j = 0; $j <= $toLength; ++$j) { Chris@0: $matrix[$j * $width] = 0; Chris@0: } Chris@0: Chris@0: for ($i = 1; $i <= $fromLength; ++$i) { Chris@0: for ($j = 1; $j <= $toLength; ++$j) { Chris@0: $o = ($j * $width) + $i; Chris@12: $matrix[$o] = \max( Chris@0: $matrix[$o - 1], Chris@0: $matrix[$o - $width], Chris@0: $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0 Chris@0: ); Chris@0: } Chris@0: } Chris@0: Chris@0: $i = $fromLength; Chris@0: $j = $toLength; Chris@0: Chris@0: while ($i > 0 && $j > 0) { Chris@12: if ($from[$i - 1] === $to[$j - 1]) { Chris@12: $common[] = $from[$i - 1]; Chris@0: --$i; Chris@0: --$j; Chris@0: } else { Chris@0: $o = ($j * $width) + $i; Chris@12: Chris@0: if ($matrix[$o - $width] > $matrix[$o - 1]) { Chris@0: --$j; Chris@0: } else { Chris@0: --$i; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@12: return \array_reverse($common); Chris@0: } Chris@0: }