Home > Backend Development > PHP Tutorial > How to Generate all Permutations of an Array in PHP?

How to Generate all Permutations of an Array in PHP?

DDD
Release: 2024-12-09 06:14:14
Original
225 people have browsed it

How to Generate all Permutations of an Array in PHP?

Generating Permutations of an Array in PHP

In PHP, generating permutations of an array involves arranging all of its elements in every possible order. For instance, given an array of strings ['peter', 'paul', 'mary'], we aim to generate the following permutations:

peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter

To address this problem, we present two PHP functions.

Function 1:

function pc_permute($items, $perms = array()) {
    if (empty($items)) { 
        echo join(' ', $perms) . "<br />";
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

$arr = array('peter', 'paul', 'mary');

pc_permute($arr);
Copy after login

Function 2:

function pc_next_permutation($p, $size) {
    for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }
    if ($i == -1) { return false; }
    for ($j = $size; $p[$j] <= $p[$i]; --$j) { }
    $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
    for (++$i, $j = $size; $i < $j; ++$i, --$j) {
         $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
    }
    return $p;
}

$set = split(' ', 'she sells seashells'); 
$size = count($set) - 1;
$perm = range(0, $size);
$j = 0;

do { 
     foreach ($perm as $i) { $perms[$j][] = $set[$i]; }
} while ($perm = pc_next_permutation($perm, $size) and ++$j);

foreach ($perms as $p) {
    print join(' ', $p) . "\n";
}
Copy after login

These functions provide two different approaches to generate permutations in PHP, allowing you to select the one that best suits your needs.

The above is the detailed content of How to Generate all Permutations of an Array 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