Suppose an array is
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
I want to call a function by providing two params (both arrays) with following permutations –
array(1) and array(2,3,4)
array(1,2) and array(3,4)
array(1,2,3) and array (4)
array(1,3) and array(2,4)
array(1,4) and array(2,3)
array(2) and array(1,3,4)
and so on...
Of course the actual arrays will be larger.
I don’t know how that “permutation” is called (it’s not a permutation even probably), but it looked promising to me exploiting the fact that the elements in the set are ordered (if not, there is the order of index, so use index instead of value) so to shift from right to left and combine all left with right combinations.
This is either possible with recursion or with a stack, I normally prefer the stack.
The usage as suggested (encapsulating the function call):
Running this with a sorted (more memory required) stack consuming strategy gives the following output (formatted in columns):
The exemplary implementation (full source-code as gist) is memory optimized and produces this order (
array_popinstead ofarray_shift):Implementation:
I hope this is useful.
Another array related algorithm: Sorting with a modulus (just for reference, while writing this one I was reminded to that matrix thing)