由单个集合生成特定大小的所有组合,PHP 代码如下
要从单个集合中生成所有特定大小的组合,代码如下 −
示例
function sampling($chars, $size, $combinations = array()) { # in case of first iteration, the first set of combinations is the same as the set of characters if (empty($combinations)) { $combinations = $chars; } # size 1 indicates we are done if ($size == 1) { return $combinations; } # initialise array to put new values into it $new_combinations = array(); # loop through the existing combinations and character set to create strings foreach ($combinations as $combination) { foreach ($chars as $char) { $new_combinations[] = $combination . $char; } } # call the same function again for the next iteration as well return sampling($chars, $size - 1, $new_combinations); } $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" }
第一次迭代表示要显示的相同字符集。如果大小为 1,则显示组合。数组初始化为“new_combinations”,并使用“forloop”对其进行循环,并且该字符串中的每个字符都与其他每个字符串联在一起。函数“sampling”使用参数(字符串、字符串的大小和数组)调用。
广告