comparison vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php @ 14:1fec387a4317

Update Drupal core to 8.5.2 via Composer
author Chris Cannam
date Mon, 23 Apr 2018 09:46:53 +0100
parents
children
comparison
equal deleted inserted replaced
13:5fb285c0d0e3 14:1fec387a4317
1 <?php declare(strict_types=1);
2 /*
3 * This file is part of sebastian/diff.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11 namespace SebastianBergmann\Diff;
12
13 final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator
14 {
15 /**
16 * {@inheritdoc}
17 */
18 public function calculate(array $from, array $to): array
19 {
20 $common = [];
21 $fromLength = \count($from);
22 $toLength = \count($to);
23 $width = $fromLength + 1;
24 $matrix = new \SplFixedArray($width * ($toLength + 1));
25
26 for ($i = 0; $i <= $fromLength; ++$i) {
27 $matrix[$i] = 0;
28 }
29
30 for ($j = 0; $j <= $toLength; ++$j) {
31 $matrix[$j * $width] = 0;
32 }
33
34 for ($i = 1; $i <= $fromLength; ++$i) {
35 for ($j = 1; $j <= $toLength; ++$j) {
36 $o = ($j * $width) + $i;
37 $matrix[$o] = \max(
38 $matrix[$o - 1],
39 $matrix[$o - $width],
40 $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0
41 );
42 }
43 }
44
45 $i = $fromLength;
46 $j = $toLength;
47
48 while ($i > 0 && $j > 0) {
49 if ($from[$i - 1] === $to[$j - 1]) {
50 $common[] = $from[$i - 1];
51 --$i;
52 --$j;
53 } else {
54 $o = ($j * $width) + $i;
55
56 if ($matrix[$o - $width] > $matrix[$o - 1]) {
57 --$j;
58 } else {
59 --$i;
60 }
61 }
62 }
63
64 return \array_reverse($common);
65 }
66 }