文字列のPHP配列が与えられた場合、例:
['peter', 'paul', 'mary']
この配列の要素のすべての可能な順列を生成するにはどうすればよいですか?すなわち:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter
文字列のPHP配列が与えられた場合、例:
['peter', 'paul', 'mary']
この配列の要素のすべての可能な順列を生成するにはどうすればよいですか?すなわち:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter
function pc_permute($items, $perms = array()) {
if (empty($items)) {
echo join(' ', $perms) . "<br />";
} 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);
}
}
}
$arr = array('peter', 'paul', 'mary');
pc_permute($arr);
また
function pc_next_permutation($p, $size) {
// slide down the array looking for where we're smaller than the next guy
for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }
// if this doesn't occur, we've finished our permutations
// the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
if ($i == -1) { return false; }
// slide down the array looking for a bigger number than what we found before
for ($j = $size; $p[$j] <= $p[$i]; --$j) { }
// swap them
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
// now reverse the elements in between by swapping the ends
for (++$i, $j = $size; $i < $j; ++$i, --$j) {
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
}
return $p;
}
$set = split(' ', 'she sells seashells'); // like array('she', 'sells', 'seashells')
$size = count($set) - 1;
$perm = range(0, $size);
$j = 0;
do {
foreach ($perm as $i) { $perms[$j][] = $set[$i]; }
} while ($perm = pc_next_permutation($perm, $size) and ++$j);
foreach ($perms as $p) {
print join(' ', $p) . "\n";
}
これにより、必要な処理が実行されます。つまり、追加のメモリを割り当てる必要がありません。結果の順列を$results配列に格納します。私はこれが課題を解決するための迅速な方法であるとかなり確信しています。
<?php
function computePermutations($array) {
$result = [];
$recurse = function($array, $start_i = 0) use (&$result, &$recurse) {
if ($start_i === count($array)-1) {
array_push($result, $array);
}
for ($i = $start_i; $i < count($array); $i++) {
//Swap array value at $i and $start_i
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
//Recurse
$recurse($array, $start_i + 1);
//Restore old order
$t = $array[$i]; $array[$i] = $array[$start_i]; $array[$start_i] = $t;
}
};
$recurse($array);
return $result;
}
$results = computePermutations(array('foo', 'bar', 'baz'));
print_r($results);
これはPHP>5.4で機能します。メイン関数のインターフェイスをクリーンに保つために、再帰に無名関数を使用しました。
私は似たようなものが必要で、探している間にこの投稿を見つけました。仕事をする次のことを書いて着陸しました。
8つのアイテムを使用すると、かなり高速に動作します(オンラインで見つけた例よりも少し高速です)が、それを超えると、実行時間が急速に増加します。結果を出力するだけでよい場合は、結果をより速く作成でき、メモリ使用量を大幅に削減できます。
print_r(AllPermutations(array('peter', 'paul', 'mary')));
function AllPermutations($InArray, $InProcessedArray = array())
{
$ReturnArray = array();
foreach($InArray as $Key=>$value)
{
$CopyArray = $InProcessedArray;
$CopyArray[$Key] = $value;
$TempArray = array_diff_key($InArray, $CopyArray);
if (count($TempArray) == 0)
{
$ReturnArray[] = $CopyArray;
}
else
{
$ReturnArray = array_merge($ReturnArray, AllPermutations($TempArray, $CopyArray));
}
}
return $ReturnArray;
}
順列の数は、配列内の項目数の階乗であることに注意してください。3つのアイテムには6つの順列があり、4つには24があり、5つには120があり、6つには720があります。
編集
これを確認するために戻ってきて、いくつかの修正を行いました。
以下は、この関数の改良版であり、使用するストレージが少なく、高速です(私が見た他のソリューションよりも高速です)。
戻り配列をパラメーターとして受け取り、参照によって渡します。これにより、実行中のデータの重複の量が減少します。
function AllPermutations($InArray, &$ReturnArray = array(), $InProcessedArray = array())
{
if (count($InArray) == 1)
{
$ReturnArray[] = array_merge($InProcessedArray, $InArray);
}
else
{
foreach($InArray as $Key=>$value)
{
$CopyArray = $InArray;
unset($CopyArray[$Key]);
AllPermutations2($CopyArray, $ReturnArray, array_merge($InProcessedArray, array($Key=>$value)));
}
}
}
ジャックの答えを少し広げました
function pc_permute($items, $perms = [],&$ret = []) {
if (empty($items)) {
$ret[] = $perms;
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
$this->pc_permute($newitems, $newperms,$ret);
}
}
return $ret;
}
これにより、実際にはすべての可能な順列を含む配列が返されます。
$options = ['startx','starty','startz','endx','endy','endz'];
$x = $this->pc_permute($options);
var_dump($x);
[0]=>
array(6) {
[0]=>
string(6) "startx"
[1]=>
string(6) "starty"
[2]=>
string(6) "startz"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[1]=>
array(6) {
[0]=>
string(6) "starty"
[1]=>
string(6) "startx"
[2]=>
string(6) "startz"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[2]=>
array(6) {
[0]=>
string(6) "startx"
[1]=>
string(6) "startz"
[2]=>
string(6) "starty"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[3]=>
array(6) {
[0]=>
string(6) "startz"
[1]=>
string(6) "startx"
[2]=>
string(6) "starty"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[4]=>
array(6) {
[0]=>
string(6) "starty"
[1]=>
string(6) "startz"
[2]=>
string(6) "startx"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[5]=>
array(6) {
[0]=>
string(6) "startz"
[1]=>
string(6) "starty"
[2]=>
string(6) "startx"
[3]=>
string(4) "endx"
[4]=>
string(4) "endy"
[5]=>
string(4) "endz"
}
[6]=> ................ a lot more
文字列の代わりに配列を取り戻す方が少し便利だと思いました。次に、結果を処理する方法(それらに参加するため、または他の何か)は、使用するアプリケーション次第です。
再帰があり、人為的な余分な引数がない単純なバージョン:
function permuteArray(array $input) {
$input = array_values($input);
// permutation of 1 value is the same value
if (count($input) === 1) {
return array($input);
}
// to permute multiple values, pick a value to put in the front and
// permute the rest; repeat this with all values of the original array
$result = [];
for ($i = 0; $i < count($input); $i++) {
$copy = $input;
$value = array_splice($copy, $i, 1);
foreach (permuteArray($copy) as $permutation) {
array_unshift($permutation, $value[0]);
$result[] = $permutation;
}
}
return $result;
}
このアルゴリズムは、紙の上でそれを行う方法としては素晴らしく、有益ですが、それ以外の場合は、同じ順列を複数回計算するため、非常に非効率的です。計算のスペースと数が指数関数的に増加するため、より大きな配列の順列を計算することは非常に非現実的であることは言うまでもありません。
この記事に基づく別のバリアントは次のとおりです:https ://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm
public static function get_array_orders( $arr ) {
$arr = array_values( $arr ); // Make sure array begins from 0.
$size = count( $arr ) - 1;
$order = range( 0, $size );
$i = 0;
$orders = [];
do {
foreach ( $order as $key ) {
$orders[ $i ][] = $arr[ $key ];
}
$i ++;
} while ( $order = self::get_next_array_order( $order, $size ) );
return $orders;
}
protected static function get_next_array_order( $order, $size ) {
// slide down the array looking for where we're smaller than the next guy
$i = $size - 1;
while ( isset( $order[ $i ] ) && $order[ $i ] >= $order[ $i + 1 ] ) {
$i --;
}
// if this doesn't occur, we've finished our permutations, the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1)
if ( $i == - 1 ) {
return false;
}
// slide down the array looking for a bigger number than what we found before
$j = $size;
while( $order[ $j ] <= $order[ $i ] ){
$j--;
}
// swap them
$tmp = $order[ $i ];
$order[ $i ] = $order[ $j ];
$order[ $j ] = $tmp;
// now reverse the elements in between by swapping the ends
for ( ++ $i, $j = $size; $i < $j; ++ $i, -- $j ) {
$tmp = $order[ $i ];
$order[ $i ] = $order[ $j ];
$order[ $j ] = $tmp;
}
return $order;
}
例:
$langs = ['en', 'fr', 'ru'];
$orders = self::get_array_orders( $langs );
print_r($orders);
出力:
Array (
[0] => Array
(
[0] => en
[1] => fr
[2] => ru
)
[1] => Array
(
[0] => en
[1] => ru
[2] => fr
)
[2] => Array
(
[0] => fr
[1] => en
[2] => ru
)
[3] => Array
(
[0] => fr
[1] => ru
[2] => en
)
[4] => Array
(
[0] => ru
[1] => en
[2] => fr
)
[5] => Array
(
[0] => ru
[1] => fr
[2] => en
)
)