首页  >  文章  >  后端开发  >  如何从集合中生成特定大小的所有组合?

如何从集合中生成特定大小的所有组合?

Linda Hamilton
Linda Hamilton原创
2024-11-17 04:02:03987浏览

How to Generate All Combinations of a Specific Size from a Set?

从集合中生成特定大小组合的算法

在统计学中,抽样是指获取总体的子集来代表整个总体。目标是从给定的一组元素生成指定大小的所有可能组合。

为了实现这一点,我们可以采用递归算法,如下所示:

function sampling($chars, $size, $combinations = array()) {

    # Initialize the starting combinations as the original set
    if (empty($combinations)) {
        $combinations = $chars;
    }

    # Base case: stop if we've reached the desired size
    if ($size == 1) {
        return $combinations;
    }

    $new_combinations = array();

    # Iterate over existing combinations and add new characters
    foreach ($combinations as $combination) {
        foreach ($chars as $char) {
            $new_combinations[] = $combination . $char;
        }
    }

    # Call the function recursively to generate the next iteration of combinations
    return sampling($chars, $size - 1, $new_combinations);
}

示例:

$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);

# Display the generated combinations
var_dump($output);
/*
Expected 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"
}
*/

以上是如何从集合中生成特定大小的所有组合?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn