PHP算法從單個集合生成特定大小的所有組合我試圖推導出一種算法,該算法生成特定大小的所有可能組合,例如接受字符數組和大小作為參數的函數,并返回組合數組。示例:假設我們有一組字符:設置A = {A,B,C}a)尺寸2的所有可能組合:(3 ^ 2 = 9)AA, AB, ACBA, BB, BCCA, CB, CCb)尺寸3的所有可能組合:(3 ^ 3 = 27)AAA, AAB, AAC,ABA, ABB, ACC,CAA, BAA, BAC,.... ad so on total combinations = 27請注意,貨幣對的大小可能大于pouplation的總大小。防爆。如果set包含3個字符,那么我們也可以創建大小為4的組合。編輯:另請注意,這與排列不同。在排列中我們不能有重復的字符,例如,如果我們使用置換算法,AA就不會出現。在統計中,它被稱為抽樣。
3 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
我會使用遞歸函數。這是一個帶有注釋的(工作)示例。希望這對你有用!
function sampling($chars, $size, $combinations = array()) { # if it's the first iteration, the first set # of combinations is the same as the set of characters if (empty($combinations)) { $combinations = $chars; } # we're done if we're at size 1 if ($size == 1) { return $combinations; } # initialise array to put new values in $new_combinations = array(); # loop through existing combinations and character set to create strings foreach ($combinations as $combination) { foreach ($chars as $char) { $new_combinations[] = $combination . $char; } } # call same function again for the next iteration return sampling($chars, $size - 1, $new_combinations);}// example$chars = array('a', 'b', 'c');$output = sampling($chars, 2);var_dump($output);/* array(9) { [0]=> string(2) "aa" [1]=> string(2) "ab" [2]=> string(2) "ac" [3]=> string(2) "ba" [4]=> string(2) "bb" [5]=> string(2) "bc" [6]=> string(2) "ca" [7]=> string(2) "cb" [8]=> string(2) "cc" } */

千巷貓影
TA貢獻1829條經驗 獲得超7個贊
一種可能的算法是:
$array_elems_to_combine = array('A', 'B', 'C');$size = 4;$current_set = array('');for ($i = 0; $i < $size; $i++) { $tmp_set = array(); foreach ($current_set as $curr_elem) { foreach ($array_elems_to_combine as $new_elem) { $tmp_set[] = $curr_elem . $new_elem; } } $current_set = $tmp_set;}return $current_set;
基本上,您要做的是獲取當前集合的每個元素并附加元素數組的所有元素。
在第一步中:('a', 'b', 'c')
在秒步之后,您將獲得結果:('aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc')
依此類推。
添加回答
舉報
0/150
提交
取消