Tetris-ing an array

后端 未结 16 1397
时光取名叫无心
时光取名叫无心 2021-01-30 15:38

Consider the following array:

/www/htdocs/1/sites/lib/abcdedd
/www/htdocs/1/sites/conf/xyz
/www/htdocs/1/sites/conf/abc/         


        
16条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 16:02

    This has de advantage of not having linear time complexity; however, for most cases the sort will definitely not be the operation taking more time.

    Basically, the clever part (at least I couldn't find a fault with it) here is that after sorting you will only have to compare the first path with the last.

    sort($a);
    $a = array_map(function ($el) { return explode("/", $el); }, $a);
    $first = reset($a);
    $last = end($a);
    for ($eqdepth = 0; $first[$eqdepth] === $last[$eqdepth]; $eqdepth++) {}
    array_walk($a,
        function (&$el) use ($eqdepth) {
            for ($i = 0; $i < $eqdepth; $i++) {
                array_shift($el);
            }
         });
    $res = array_map(function ($el) { return implode("/", $el); }, $a);
    

提交回复
热议问题