duancong7573 2015-12-07 02:17
浏览 42
已采纳

在PHP中查找“最常见”数组?

I need to find a "greatest common" array for given arrays in PHP (I'm not even sure what that term should be. What I mean is an array the elements of which can be sequencially combined to form the same elements of the input arrays). The input arrays may have different count() results, but they are always unidimensional, always contain only integers and always have the same array_sum() result.

Example:

$a = array(4,6);
$b = array(5,5);
$c = array(5,1,4);

What is the best way to find (in this case) this array

$gca = array(4,1,1,4);

?

  • 写回答

1条回答 默认 最新

  • dongtangyi8962 2015-12-07 03:25
    关注

    Things got a lot easier after transforming those numbers in totals, instead of working with intervals/durations. This way, the original arrays turned into these:

    $a = array(4,10);
    $b = array(5,10);
    $c = array(5,6,10);
    

    Then it was a matter of merging the arrays, removing duplicate values and sorting, just before converting the elements back to intervals. Output of the proposed function is

    array(4,1,1,4)
    

    as intended.

    Any improvement on the function is appreciated.

    $arr[] = array(4,6);
    $arr[] = array(5,5);
    $arr[] = array(5,1,4);
    
    function findCommonDurations($arr) {
        $absolute_result = $result = array();
        foreach($arr as $key => $value) {
            $temp_arr = array();
            $so_far = 0;
            foreach($value as $key2 => $value2) {
                $temp_arr[] = $value2 + $so_far;
                $so_far += $value2;
            }
            $absolute_result = array_merge($absolute_result, $temp_arr);
        }
        $absolute_result = array_unique($absolute_result);
        sort($absolute_result);
    
        $result[0] = $absolute_result[0];
        for ($i = 1, $n = count($absolute_result); $i < $n; $i++) {
            $result[] = $absolute_result[$i] - $absolute_result[$i-1];
        }
        return($result);
    }
    
    print_r(findCommonDurations($arr));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备