-1

単純な配列をループして、次のような要素のすべての可能な組み合わせを見つけるのに助けが必要です:

array('a', 'b', 'c');

期待される結果は次のとおりです。

array(
     0=>array('a', 'a', 'a'),
     1=> array('a', 'a', 'b')
);

私は完全に途方に暮れており、どんな助けや指針も大歓迎です!

これは私がこれまでに持っているものです。

$array = array('red', 'blue', 'green', 'white');
$count = count($array);

$current = array_fill(0, $count, $array[0]);
$last = array_fill(0, $count, end($array));


$output = array();
$i = 0;

while ($current != $last) {
    $indexes = str_pad($i, $count, "0", STR_PAD_LEFT);

    $j = str_split($indexes);

    foreach ($j as $a => $b) {
        if (isset($array[$b])) {
            $output[$i][] = $array[$b];
        }
    }
    $current = $output[$i];
    $i++;
}
// cleaver duplication removal
$result = array_map("unserialize", array_unique(array_map("serialize", $output)));

echo '<pre>';
    print_r($result);
echo '</pre>';

重複除去コードはこちらから。

4

1 に答える 1

1
function pc_permute($items, $perms = array( )) {
    if (empty($items)) { 
        print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

ソース。

于 2012-08-29T18:52:05.813 に答える