i have an array
$a = array(1,2,3,4,5);
i want to get all combination of $n
elements in array
$n = 3
output
1 2 3
1 3 4
1 4 5
2 3 5
2 4 5
.
.
.
5 1 2
i have an array
$a = array(1,2,3,4,5);
i want to get all combination of $n
elements in array
$n = 3
output
1 2 3
1 3 4
1 4 5
2 3 5
2 4 5
.
.
.
5 1 2
You would essentially go from start to end in your array placing the current number at the start, then append all permutations of the array without the number at the start to the array. If you use recursion, that's fairly simple. Example:
input: [1] [2] [3]
step 1: [1] [unknown] [unknown]
now call the function for generating all permutations (this function) and append all the arrays you get to that.
The amount of iterations you need for each function call is n!
(n)*(n-1)*(n-2) ...
.
Awhile back I had a similar question for something I was doing for my day job (which isn't a programmer). I found a javascript version for the following code. Hopefully I've transcoded it well enough. Comments by me. If you can wait awhile (going on vacation soon) then I can work out how to limit the recursion calls to make it less resource heavy.
<?php
function combinations($arr){
$result = array();
//the result array, returned by this outer function.
function fn($active, $rest, &$a){
if(!$active && !$rest)
return;//If we have empty arrays, stoppit
if(!$rest){
//Are we out of remaining options? Yep, add the active array.
$a[] = $active;
}else{
/*
we are currently splitting the work between the two options. First is that we compute the
combinations of the currently $active and the $rest array offset by 1.
*/
fn($active, array_slice($rest,1), $a);
$active[] = $rest[0];
//Next we add in the first element of the rest array to the active array, and slice off that new element to avoid duplicates.
fn($active, array_slice($rest,1), $a);
}
} //Function that actually does the work;
fn([],$arr,$result);
return $result;
}
$combos = combinations([1,2,3,4,5]);
$combos = array_filter($combos,function($item){
return count($item) == 2;
});
print_r($combos);
?>