這裏是一個非常更新答案(最初從這個答案更新] 1)你的問題:
function findPermutations($arr, $arrLen, $size, $perArr = array(), $pos = 0, &$found = array()) {
if ($size==$pos) { //if $pos reach $size then we have found one permutation
$found[] = vsprintf("%s%s|%s%s|%s%s", $perArr);
return;
}
for ($i=0; $i<$arrLen; $i++) {
$perArr[$pos] = $arr[$i]; //put i'th char in current position
//The recursive call that move to next position with $pos+1
findPermutations($arr, $arrLen, $size, $perArr, $pos+1, $found);
}
return $found;
}
$permutations = array();
$letters = array('1','2','3');
$max_length = 6;
$permutations = findPermutations($letters, count($letters), $max_length);
for($i = 0; $i < count($permutations); $i++) {
print ($permutations[$i].'<br/>');
}
下面是我在做什麼。我通過引用傳入一個名爲$permutations
的空數組,並且當我找到新的排列組合時,我將它們附加到它。當功能findPermutations()
完成後,我最終得到一個所有排列的數組,我可以迭代或插入。爲了獲得我使用的格式,vsprintf,它允許我傳遞一組數據並應用格式(在這種情況下爲%s%s|%s%s|%s%s
)。最後,我使用默認參數值來調用這個函數更清晰。
http://stackoverflow.com/questions/5506888/permutations-all-possible-sets-of-numbers –
忘記分隔符,你可以隨時添加它們。只需要選擇一個隨機數(1到3之間)6次,並將它們連接在一起。檢查你的數據庫表,看看它是否存在,如果沒有添加它。運行它一堆。最終你會得到他們。 –
此外,管道分隔符只是象徵性的,它對排列算法沒有任何重要性,所以不要認爲它是一個複雜的' –