3

假设我有一个这样的数组:

$arr_sequences = 
    array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');

如何对数组进行排序,使值如下所示:

$arr_sequences = 
    array('00-02', '02-03', '03-23', '23-03', '03-07', '07-11', '11-11', '11-10');

如果我们仔细观察,每个值都有一个 id(代码)除以-
例如:

$arr_sequences[2] = '03-07'; // '07' as last code, then search another value with '07' in front of the value

那么下一个索引值应该是

$arr_sequences[5] = '07-11'; // '07' front, then search '11' as next value

目标是在不丢失任何长度的情况下对数组进行排序。

我已经尝试过使用树算法,但我无法让它工作。

4

2 回答 2

3

疯狂的做法:

  1. 生成所有可能的排列
  2. 循环遍历每个排列,看看是否有多米诺骨牌效应并将其添加到输出中

PHP 代码

$arr_sequences = array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11'); // Input

$permutations = permutations($arr_sequences); // Generating permutations

// Generating a regex
$n = count($arr_sequences);
$regex = '\d+';
for($i=1;$i<$n;$i++){
    $regex .= '-(\d+)-\\'.$i;
}
$regex .= '-\d+';

$sorted = preg_grep('#'.$regex.'#', $permutations); // Filtering the permutations
sort($sorted); // re-index the keys

//generating the desired output
$output = array();
foreach($sorted as $key => $sample){
    $temp = explode('-', $sample);
    $c = count($temp); // Micro-optimization, yeaaaah!
    for($i=0;$i<$c;$i+=2){
        $output[$key][] = $temp[$i] . '-' . $temp[$i+1];
    }
}

print_r($output); // printing

// Function from http://stackoverflow.com/a/14998162
function permutations($elements) {
    if(count($elements)<2) return $elements;
    $newperms= array();
    foreach($elements as $key=>$element) {
        $newelements= $elements;
        unset($newelements[$key]);

        $perms= permutations($newelements);
        foreach($perms as $perm) {
            $newperms[]= $element."-".$perm;
        }
    }
    return $newperms;
}

输出

Array
(
    [0] => Array
        (
            [0] => 00-02
            [1] => 02-03
            [2] => 03-23
            [3] => 23-03
            [4] => 03-07
            [5] => 07-11
            [6] => 11-11
            [7] => 11-10
        )

)

似乎只有一种解决方案:p

于 2013-07-15T12:27:20.770 回答
1

一种蛮力方式,在 php.ini 中。(未测试):

<?php

$arr = array('00-02', '02-03', '03-07', '23-03', '03-23', '07-11', '11-10', '11-11');

function findMatches($i, $val_ignore, $arr) {
    $arr_matches = array();
    foreach($arr as $key => $val) {
      $j = substr_replace($val, '', 2);
      if (($i == $j) && ($val != $val_ignore))
        $arr_matches[] = $val;
    }
    return $arr_matches;
}

$arr_sorted = array();
foreach($arr as $key => $val) {
    $i = substr_replace($val, '', 0, 3);
    if (!in_array($val, $arr_sorted)) $arr_sorted[] = $val;
    $arr_sorted = array_merge($arr_sorted, findMatches($i, $val, $arr));
}

?>
于 2013-07-15T12:32:52.333 回答