Home >Backend Development >PHP Tutorial >How Can I Generate All Combinations of a Specific Size from a Character Set?

How Can I Generate All Combinations of a Specific Size from a Character Set?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-27 12:11:131072browse

How Can I Generate All Combinations of a Specific Size from a Character Set?

Determining All Combinations of Specified Sizes from a Character Set

This inquiry seeks an algorithm capable of generating all potential combinations of a certain size from a given set of characters. Let's delve into a solution using a recursive function:

function sampling($chars, $size, $combinations = array()) {
    if (empty($combinations)) {
        $combinations = $chars;
    }
    if ($size == 1) {
        return $combinations;
    }
    $new_combinations = array();
    foreach ($combinations as $combination) {
        foreach ($chars as $char) {
            $new_combinations[] = $combination . $char;
        }
    }
    return sampling($chars, $size - 1, $new_combinations);
}

Consider an example with $chars = ['a', 'b', 'c']:

$output = sampling($chars, 2);
var_dump($output);

The output displays all possible combinations of size 2:

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"
}

This recursive approach effectively generates all combinations, ensuring that even combinations of sizes larger than the initial set are accommodated.

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

Statement:
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