从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”进行循环,并且该字符串中的每个字符都与其他所有字符连接在一起。使用参数(字符串,字符串的大小和数组)调用函数“采样”。
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短