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
        )

)

解決策は 1 つしかなかったようです :p

于 2013-07-15T12:27:20.770 に答える