我得到了一個任務,讓我有點瘋狂,有處理字排列的部分,之後我瀏覽互聯網,我發現一個函數來完成排列,如下圖所示:如何創建一個字符串(10個字符或更長)的排列?
function permute($str) {
if (strlen($str) < 2) {
return array($str);
}
$permutations = array();
$tail = substr($str, 1);
foreach (permute($tail) as $permutation) {
$length = strlen($permutation);
for ($i = 0; $i <= $length; $i++) {
$permutations[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
}
}
return $permutations;
}
這顯示結果:
print_r(array_unique(permute("abcdefghi"))); // found 362880
print_r(array_unique(permute("abcdefghij"))); // error
的問題是,此功能僅能夠執行的9個字符的所有置換(約362880點的組合,具有很長的時間,使瀏覽器不響應的tinytime)。當試圖執行多達10個字符的排列,會出現一條錯誤消息:
致命錯誤:用盡134217728個字節允許內存大小(試圖分配35個字節)
你有一個解決方案或另一種方式做10個或更多字符的排列?
你試圖做一個簡單的隨機字符串發生器?因爲如果是的話,我已經創建了一個,所以我可以發送給你... – 2012-02-11 05:14:51
可能重複[在PHP中的字符串排列](http://stackoverflow.com/questions/8130411/permutation-for-string-in- php) – nickb 2012-02-11 05:16:11
在整數數字中,您試圖製作一個由每個包含10個字符的400萬個字符串組成的數組。這是40兆字節加上開銷。錯誤消息說,有130兆字節的限制。所以在開銷的情況下,你想要的輸出太大了,這聽起來似乎是合理的。計算不同的東西(一次產生一個排列,而不是一次產生排列?)或增加你的限制。 – 2012-02-11 05:20:44