RE: [PHP] Generate every possible combination

From: Date: Fri, 17 May 2002 02:27:53 +0000
Subject: RE: [PHP] Generate every possible combination
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-98000@lists.php.net to get a copy of this message
Here's the function I use: // array array_permute(array [, string]) // // Returns an array containing the permutations of the values in an array. // // Example: // $a = array(1, 2, 3); // $p = array_permute($a) // // Result: // p[0] = '1,2,3' // p[1] = '1,3,2' // p[2] = '2,1,3' // p[3] = '2,3,1' // p[4] = '3,2,1' // p[5] = '3,1,2' // function array_permute(&$a, $glue = ',') { $retval = array(); array_permute_internal($a, $glue, $retval, 0, count($a)); return $retval; } // Private function used by array_permute. function array_permute_internal(&$a, $glue, &$retval, $depth, $ubound) { if ($ubound > 0) { for ($i=0; $i < $ubound; $i++) { $c = $a[$depth+$i]; $a[$depth+$i] = $a[$depth]; $a[$depth] = $c; array_permute_internal($a, $glue, $retval, $depth+1, $ubound-1); $c = $a[$depth+$i]; $a[$depth+$i] = $a[$depth]; $a[$depth] = $c; } } else { $retval[] = implode($glue, $a); } } -----Original Message----- From: Evan Nemerson [mailto:evan@coeus-group.com] Sent: Thursday, May 16, 2002 12:17 AM To: php-general@lists.php.net Subject: [PHP] Generate every possible combination I need to generate every possible combination of the the values in an array. For example, if... $array = Array("A", "B", "C"); I want to be able to do something like print_r(magic_function($array)); which would output Array ( [0] => "ABC" [1] => "ACB" [2] => "BAC" [3] => "BCA" [4] => "CAB" [5] => "CBA" ) I really have no idea where to begin. The best lead I can think of is that there are going to be n! elements in the output array, where n is the size of the input array. Any help would be greatly appreciated. Evan -- Think not those faithful who praise all thy words and actions, but those who kindly reprove thy faults. Socrates -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php

« previous php.general (#98000) next »