php中阶乘的置换
我不知道怎么解释。但也许下面的例子可以让你们理解我的问题是什么 例如: 我有一个包含3个元素的数组php中阶乘的置换,php,permutation,factorial,Php,Permutation,Factorial,我不知道怎么解释。但也许下面的例子可以让你们理解我的问题是什么 例如: 我有一个包含3个元素的数组 $elements = array( 'A', 'B', 'C' ); 排列将是3:3。因此,结果是: A-B-C ; A-C-B ; B-A-C ; B-C-A ; C-A-B; C-B-A 我不想要任何3取2或3取1的排列,就像你们在例子中看到的3取3。如果我在一个数组中有4个元素,排列是4:4。等等 (我认为排列的数量是3!=1*2*3=6个排列,4!=1*2*3*4=24个排列……这就
$elements = array( 'A', 'B', 'C' );
排列将是3:3。因此,结果是:
A-B-C ; A-C-B ; B-A-C ; B-C-A ; C-A-B; C-B-A
我不想要任何3取2或3取1的排列,就像你们在例子中看到的3取3。如果我在一个数组中有4个元素,排列是4:4。等等
(我认为排列的数量是3!=1*2*3=6个排列,4!=1*2*3*4=24个排列……这就是为什么我称之为阶乘排列。)
如果有其他问题和答案与我的问题类似,请让我知道使用递归函数:
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;
}
函数置换($elements){
if(计数($element)$element){
$newelements=$elements;
未设置($newelements[$key]);
$perms=排列($newelements);
foreach($perms作为$perm){
$newperms[]=$element.“-”$perm;
}
}
返回$newperms;
}
没有测试它,所以您仍然有工作;-) 不确定您需要什么,但您是否正在尝试生成这些排列 这应该让你开始,它将执行一个完整的排列对任何大小的设置你需要。添加了一些注释,您应该能够理解
$array = array('A','B','C', 'D');
$permutations = array($array);
$perm_pool = range(0, count($array)-1);
function getPermutation($p, $size){
// we pass in an array of integers, basically pointers, we want to see when we've fully reversed the set
for ($i = $size-1; $p[$i] >= $p[$i+1]; $i--){}
// the array starts at [1,2,3,4], when we've reached [4,3,2,1], we're done.
if ($i == -1) { return false; }
// slide down to the next largest number, this will be our next swap
for ($j = $size; $p[$j] <= $p[$i]; $j--) {}
// swap it
$tmp = $p[$i];
$p[$i] = $p[$j];
$p[$j] = $tmp;
// reverse the arrangement by swapping the head and tails
for ($i++, $j = $size; $i < $j; $i++, $j--){
$tmp = $p[$i];
$p[$i] = $p[$j];
$p[$j] = $tmp;
}
return $p;
}
$i=1;
while($perm_pool=getPermutation($perm_pool, count($array)-1)){
foreach($perm_pool as $p){
$permutations[$i][] = $array[$p];
}
$i++;
}
$array=array('A','B','C','D');
$permutations=数组($array);
$perm_pool=范围(0,计数($array)-1);
函数getPermutation($p,$size){
//我们传入一个整数数组,基本上是指针,我们想看看什么时候我们完全反转了这个集合
对于($i=$size-1;$p[$i]>=$p[$i+1];$i--){}
//数组从[1,2,3,4]开始,当我们到达[4,3,2,1]时,就完成了。
如果($i==-1){返回false;}
//滑到下一个最大的数字,这将是我们的下一次交换
对于($j=$size;$p[$j]我不知道如何开始!只有23个,应该有24Ah是的,排列集不包括原始的排列集。检查编辑-将其添加到初始排列集中,并将while循环偏移1。这对2,3,4有效;1中循环有效;无论如何,逻辑不错。我将处理它,使其发挥所有价值。谢谢@Atticus