|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the PHP-LCS package. |
| 5 | + * |
| 6 | + * Copyright © 2012 Erin Millard |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Ezzatron\LCS; |
| 13 | + |
| 14 | +class LCSSolver |
| 15 | +{ |
| 16 | + /** |
| 17 | + * Returns the longest common subsequence of the given arrays. |
| 18 | + * |
| 19 | + * See http://en.wikipedia.org/wiki/Longest_common_subsequence_problem |
| 20 | + * |
| 21 | + * @param array $left The first array. |
| 22 | + * @param array $right The second array. |
| 23 | + * @param array $additional,... Any number of additional arrays. |
| 24 | + * |
| 25 | + * @return array The longest common subsequence. |
| 26 | + */ |
| 27 | + public function longestCommonSubsequence(array $left, array $right) |
| 28 | + { |
| 29 | + if (func_num_args() > 2) { |
| 30 | + $arguments = func_get_args(); |
| 31 | + array_splice( |
| 32 | + $arguments, |
| 33 | + 0, |
| 34 | + 2, |
| 35 | + array( |
| 36 | + $this->longestCommonSubsequence($left, $right) |
| 37 | + ) |
| 38 | + ); |
| 39 | + |
| 40 | + return call_user_func_array( |
| 41 | + array($this, 'longestCommonSubsequence'), |
| 42 | + $arguments |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + $m = count($left); |
| 47 | + $n = count($right); |
| 48 | + |
| 49 | + // $a[$i][$j] = length of LCS of $left[$i..$m] and $right[$j..$n] |
| 50 | + $a = array(); |
| 51 | + |
| 52 | + // compute length of LCS and all subproblems via dynamic programming |
| 53 | + for ($i = $m - 1; $i >= 0; $i--) { |
| 54 | + for ($j = $n - 1; $j >= 0; $j--) { |
| 55 | + if ($left[$i] === $right[$j]) { |
| 56 | + $a[$i][$j] = |
| 57 | + ( |
| 58 | + isset($a[$i + 1][$j + 1]) ? |
| 59 | + $a[$i + 1][$j + 1] : |
| 60 | + 0 |
| 61 | + ) + |
| 62 | + 1 |
| 63 | + ; |
| 64 | + } else { |
| 65 | + $a[$i][$j] = max( |
| 66 | + ( |
| 67 | + isset($a[$i + 1][$j]) ? |
| 68 | + $a[$i + 1][$j] : |
| 69 | + 0 |
| 70 | + ), |
| 71 | + ( |
| 72 | + isset($a[$i][$j + 1]) ? |
| 73 | + $a[$i][$j + 1] : |
| 74 | + 0 |
| 75 | + ) |
| 76 | + ); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + // recover LCS itself |
| 82 | + $i = 0; |
| 83 | + $j = 0; |
| 84 | + $lcs = array(); |
| 85 | + |
| 86 | + while($i < $m && $j < $n) { |
| 87 | + if ($left[$i] === $right[$j]) { |
| 88 | + $lcs[] = $left[$i]; |
| 89 | + |
| 90 | + $i++; |
| 91 | + $j++; |
| 92 | + } elseif ( |
| 93 | + ( |
| 94 | + isset($a[$i + 1][$j]) ? |
| 95 | + $a[$i + 1][$j] : |
| 96 | + 0 |
| 97 | + ) >= |
| 98 | + ( |
| 99 | + isset($a[$i][$j + 1]) ? |
| 100 | + $a[$i][$j + 1] : |
| 101 | + 0 |
| 102 | + ) |
| 103 | + ) { |
| 104 | + $i++; |
| 105 | + } else { |
| 106 | + $j++; |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return $lcs; |
| 111 | + } |
| 112 | +} |
0 commit comments