Home > Backend Development > PHP Tutorial > How to Generate All Combinations from a 1D Array in PHP Using a Recursive Depth-First Search?

How to Generate All Combinations from a 1D Array in PHP Using a Recursive Depth-First Search?

DDD
Release: 2024-10-30 18:32:02
Original
758 people have browsed it

How to Generate All Combinations from a 1D Array in PHP Using a Recursive Depth-First Search?

Getting All Combinations of a 1D Array

The task of assembling all attainable combinations from a one-dimensional array can be achieved by utilizing a recursive method. This approach encompasses a depth-first search approach, exploring every possible combination while maintaining the integrity of each element's arrangement.

Consider the following PHP code, which effectively handles the aforementioned task:

<code class="php"><?php

$array = array('Alpha', 'Beta', 'Gamma', 'Sigma');

function depth_picker($arr, $temp_string, &$collect) {
    if ($temp_string != "") 
        $collect []= $temp_string;

    for ($i=0, $iMax = sizeof($arr); $i < $iMax; $i++) {
        $arrcopy = $arr;
        $elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
        if (sizeof($arrcopy) > 0) {
            depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
        } else {
            $collect []= $temp_string. " " . $elem[0];
        }   
    }   
}

$collect = array();
depth_picker($array, "", $collect);
print_r($collect);

?></code>
Copy after login

This implementation operates by traversing the input array recursively, analyzing each element and its potential impact on the overall combination set. When an element is included in the combination, a new array without that element is created for further exploration. This process continues until all elements are examined and the full spectrum of combinations is captured.

By employing this approach, you can successfully retrieve every possible combination from the provided 1D array, satisfying the requirements of retaining both the original sequence and featuring distinct arrangements.

The above is the detailed content of How to Generate All Combinations from a 1D Array in PHP Using a Recursive Depth-First Search?. 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