如何比较大数组中的关键序列,找出最大数量的重复序列?

时间:2017-04-18 11:26:02

标签: php arrays preg-match

我已经比较了矩阵的数据,我已经计算了数组的数据,但是我从未计算过,数组之间重复键的顺序是什么,我想在所有序列之间进行比较,以及找出这个部分的最大大小重复..我有数百个数字,我应该在它们之间进行比较,并找出它们之间最大的重复范围,序列中存在的最大重复大小,以及它们中也存在另一个大阵列的序列!

可以使用in_array()简单地查找重复的单个元素。使用array_keys()重复来自不同数组的键也很容易。由于我们关注的是序列而不是单个值,因此它们都没有真正帮助我们。

<?php
header('Content-Type: text/html; charset=utf-8');
echo 'test - This is just for us to figure out, what is the size of the greatest duplication of stretches between the previous sequences'.'<br>';


$previous_results_manually_inserted = array(
 array('12','21','34','1','51','87','42','49','37','119','101','7','111','17','11','19','2','15','6'),
 array('3','5','1','18','61','75','92','84','36','81','2','07','90','2','71','17','08','51','37'),
 array('81',75','92','84','36','81','2','07','90','2','17','65','44','73','27','30','41','74','88'),
);

foreach ( $previous_results_manually_inserted as $previous ) {

         $match = preg_match("/.*$test.*/", $previous );
}    

echo 'The largest repeated slice between these sequences is:'; 
echo implode(', ',  $match ), "<br>\n"

输出:75&#39;,&#39; 92&#39;&#39; 84&#39;&#39; 36&#39;&#39; 81&#39;&#39; 2&#39;&#39; 07&#39;&#39; 90&#39;&#39 2&#39;

注意:最终目标:最高的两面性是9个数字。 (在这个例子中)

谢谢大家。

1 个答案:

答案 0 :(得分:0)

该任务与查找最大公共字符串的算法非常相似。可以解决如下:

$arrs = [
 ['12','21','34','1','51','87','42','49','37','119','101','7','111','17','11','19','2','15','6'],
 ['3','5','1','18','61','75','92','84','36','81','2','07','90','2','71','17','08','51','37'],
 ['81','75','92','84','36','81','2','07','90','2','17','65','44','73','27','30','41','74','88'],
];
$sequence = [];
foreach($arrs as $offset => $item){
    $sarr = array_slice($arrs , $offset+1);
    $count = count($item);
    foreach($sarr as $arr){
        $str = join(',',$arr);
        for($a = 0;$a<$count;$a++){
            for($b = 1;$b<$count;$b++){
                $needle = join(',',array_slice($item , $a , ($a + $b > $count ? $count : $b)));
                if(strpos($str,$needle) !== false){
                    $sequence[(substr_count($needle,','))] = $needle;
                }
            }
        }
    }
}
echo array_pop($sequence).PHP_EOL;

//out : 75,92,84,36,81,2,07,90,2