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

Linda Hamilton
Release: 2024-11-17 04:02:03
Original
987 people have browsed it

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

Algorithm to Generate Combinations of Specific Size from a Set

In statistics, sampling refers to obtaining a subset of a population to represent the entire population. The goal is to generate all possible combinations of a specified size from a given set of elements.

To achieve this, we can employ a recursive algorithm, as demonstrated below:

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);
}
Copy after login

Example:

$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"
}
*/
Copy after login

The above is the detailed content of How to Generate All Combinations of a Specific Size from a Set?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template