2012-12-24 150 views

回答

9

這裏的另一種方式。

此功能的增量在鹼

([在數組元素的數]),並使用strtr函數的效率函數換出的字符的字符串。

function everyCombination($array) { 

    $arrayCount  = count($array); 
    $maxCombinations = pow($arrayCount, $arrayCount); 
    $returnArray  = array(); 
    $conversionArray = array(); 

    if ($arrayCount >= 2 && $arrayCount <= 36) 
    { 
     foreach ($array as $key => $value) { 
      $conversionArray[base_convert($key, 10, $arrayCount)] = $value; 
     } 

     for ($i = 0; $i < $maxCombinations; $i++) { 
      $combination = base_convert($i, 10, $arrayCount); 
      $combination = str_pad($combination, $arrayCount, "0", STR_PAD_LEFT); 
      $returnArray[] = strtr($combination, $conversionArray); 
     } 

     return $returnArray; 
    } 

    echo 'Input array must have between 2 and 36 elements'; 
} 

則...

print_r(everyCombination(array('a', 'b', 'c', 'd'))); 

這也似乎比下面的遞歸例如更快的是顯著。我的服務器上

使用microtime中()這個代碼0.072862863540649秒

下面的遞歸示例採用0.39673089981079秒運行。

快138%!

+1

這工作完美 - 謝謝! – user1926784

+1

這是一段很棒的代碼。 +1 – Peter

4

您應該使用遞歸函數

function perm($arr, $n, $result = array()) 
{ 
    if($n <= 0) return false; 
    $i = 0; 

    $new_result = array(); 
    foreach($arr as $r) { 
    if(count($result) > 0) { 
     foreach($result as $res) { 
       $new_element = array_merge($res, array($r)); 
       $new_result[] = $new_element; 
      } 
     } else { 
      $new_result[] = array($r); 
     } 
    } 

    if($n == 1) return $new_result; 
    return perm($arr, $n - 1, $new_result); 
} 

$array = array('a', 'b', 'c', 'd'); 
$permutations = perm($array, 4); 
print_r($permutations); 
+1

這是在互聯網上找到的唯一方法,它實際上做我所需要的! – Dejv