-
- function Permutation($arr, $size = 1) {
- $len = count($arr);
- $start = array_slice(array_keys($arr), 0, $size);
- $end = array_reverse(array_slice(array_keys($arr),-$size));
- $r_arr = array();
- do {
- if ( compare($end, $start)<0 ) break;
- if (array_unique ($start) != $start) continue;
- $t = array();
- foreach ($start as $k) {
- $t[] = $arr[$k];
- }
- $r_arr[] = $t;
- } while ( $start = addone($start, $len) );
- return $r_arr;
- }
-
-
- function addone ($arr, $max_num) {
- $size = count($arr);
- for ($i=$size-1; $i>=0; $i--) {
- if ($arr[$i] + 1 < $max_num) {
- $arr[$i]++;
- return $arr;
- } else {
- if ($i == 0) return false;
- $arr[$i] = 0;
- }
- }
- }
-
-
- function compare ($a, $b) {
- for ($i=0; $i<count($a); $i++) {
- if ($a[$i] != $b[$i]) {
- return $a[$i]>$b[$i] ? 1 : -1;
- }
- }
- return 0;
- }
-
- $p = Permutation(array(1,2,3,4,5), 4);
- echo '<pre>';
- print_r($p);
- echo '</pre>';
- exit;