Home > Backend Development > PHP Tutorial > How to Generate All Combinations of a Specific Size from a Single Set in PHP?

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

DDD
Release: 2024-11-29 01:03:11
Original
176 people have browsed it

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

How to Generate All Combinations of a Specific Size from a Single Set in PHP

Given an array of characters and a desired combination size, the task is to generate all possible combinations of that specific size. This article explores an algorithm to achieve this using PHP, differentiating it from permutations where repeating characters are not allowed.

Algorithm

The algorithm is based on recursion. Here's a detailed explanation:

  1. Initialization: If the algorithm is running for the first time, the initial set of combinations is set to the given character array.
  2. Checking Size: If the desired combination size is 1, the current set of combinations is returned as the result.
  3. Creating New Combinations: For each combination in the current set and each character in the original array, a new combination is created by concatenating the current combination and the character.
  4. Recursive Call: The function is recursively called with the new set of combinations and a decrement of the desired combination size.
  5. Result: The final result is the returned output after the recursion completes.

Example Implementation

Below is a working example in PHP:

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);

}

// Example
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);
Copy after login

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 Single Set in PHP?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template