我整天都在看PHP数组排列/组合问题..但仍然无法弄明白:/
如果我有一个像这样的数组:
20 //key being 0
20 //key being 1
22 //key being 2
24 //key being 3
我需要组合如:
20, 20, 22 //keys being 0 1 2
20, 20, 24 //keys being 0 1 3
20, 22, 24 //keys being 0 2 3
20, 22, 24 //keys being 1 2 3
我目前的代码给了我:
20, 22, 24
因为它不想重复20 ...但这就是我需要的!
这是我的代码 . 它直接来自Php recursion to get all possibilities of strings
function getCombinations($base,$n){
$baselen = count($base);
if($baselen == 0){
return;
}
if($n == 1){
$return = array();
foreach($base as $b){
$return[] = array($b);
}
return $return;
}else{
//get one level lower combinations
$oneLevelLower = getCombinations($base,$n-1);
//for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add
$newCombs = array();
foreach($oneLevelLower as $oll){
$lastEl = $oll[$n-2];
$found = false;
foreach($base as $key => $b){
if($b == $lastEl){
$found = true;
continue;
//last element found
}
if($found == true){
//add to combinations with last element
if($key < $baselen){
$tmp = $oll;
$newCombination = array_slice($tmp,0);
$newCombination[]=$b;
$newCombs[] = array_slice($newCombination,0);
}
}
}
}
}
return $newCombs;
}
我一直在玩 ($b == $lastEl)
线,没有运气
===============
我已经看过的问题,并且与创建内存不足错误的OR不同!:
-
How can I get all permutations in PHP without sequential duplicates?
-
How can I get all permutations in PHP without sequential duplicates?
-
Find combination(s) sum of element(s) in array whose sum equal to a given number
-
Find unique combinations of values from arrays filtering out any duplicate pairs
-
Finding all the unique permutations of a string without generating duplicates
我已尝试使用12个项目的数组中的一些算法,并最终耗尽内存 . 然而,我目前使用的算法并没有给我一个内存不足的错误....但是......我需要那些重复!
6 回答
如果您不介意使用几个全局变量,可以在PHP中执行此操作(从JavaScript中的version翻译):
OUTPUT:
梨包Math_Combinatorics使这种问题相当容易 . 它只需要相对较少的代码,简单直接,而且非常容易阅读 .
如果我必须将其打包为函数,我会做这样的事情 .
这将返回一个数组数组 . 获取文本 . . .
想法很简单 . 假设您知道如何置换,那么如果您将这些排列保存在集合中,它就会变成组合 . 按定义设置处理重复值 . Set或HashSet的Php等效是SplObjectStorage,ArrayList是Array . 重写应该不难 . 我有一个Java实现:
为什么不使用二进制?至少它的简单和非常容易理解每行代码是什么样的?这是我在一个项目中为自己写的一个函数,我觉得它非常整洁!
对于您的示例,此输出:
有同样的问题,发现了一个不同的,按位的,更快的解决方案:
这个生成从0到n-1的整数的所有大小m组合,因此例如m = 2,n = 3并且调用comb(2,3)将产生:
它为您提供索引位置,因此很容易通过索引指向数组元素 .
Edit: 输入梳子失败(30,5) . 不知道为什么,有人有什么想法吗?
使用strrev和/ foreach循环清理Adi Bradfield的消化,并且只获得独特的结果 .