Generate All Permutations of a PHP Array
Problem:
Given an array of strings, generate all possible permutations of its elements. For example, for the array ['peter', 'paul', 'mary'], we should obtain:
Solution 1: pc_permute Function
This function uses recursion to swap and reorder elements within the array, generating permutations.
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); } } }
Solution 2: pc_next_permutation Function
An alternative approach is to utilize the next permutation algorithm.
function pc_next_permutation($p, $size) { // Find the largest index i where p[i] < p[i+1] for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { } // If i is -1, no next permutation exists if ($i == -1) { return false; } // Find the largest index j where p[j] > p[i] for ($j = $size; $p[$j] <= $p[$i]; --$j) { } // Swap p[i] and p[j] $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; // Reverse the order of the elements from i+1 to size for (++$i, $j = $size; $i < $j; ++$i, --$j) { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } return $p; }
Usage:
$arr = array('peter', 'paul', 'mary'); pc_permute($arr); or $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"; }
Reference:
The above is the detailed content of How to Generate All Permutations of a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!