I simply cannot wrap my head around how to solve this problem and after a thorough search on Google with no results, I turn to you with hopes of a solution.
Given the sa
Supposing you have only one nesting level, what you want is:
$my_ar[group1][0].(rest_of_the_group_perms[0])
$my_ar[group1][0].(rest_of_the_group_perms[1])
...
$my_ar[group1][N].(rest_of_the_group_perms[K])
that is, you can see the problem as having to join two lists/arrays. The first being the first subarray of your array and the second being the (recursively already made) rest.
So you need a function like this:
perms($my_arr) {
foreach($elem in $group1) {
$return_list[] = $elem.$rest;
}
}
where $group1
is the first subarray of your array and $group_rest
is what is left. So:
perms($my_arr) {
$group1 = head($my_arr);
$group_rest = tail($my_arr);
$rest = perms($group_rest);
$return_list = array();
foreach($elem in $group1) {
$return_list[] = "$elem, $rest";
}
return $return_list;
}
but $rest
is also an array so you have to loop over that too:
perms($my_arr) {
$group1 = head($my_arr);
$group_rest = tail($my_arr);
$rest = perms($group_rest);
$return_list = array();
foreach($elem in $group1) {
foreach($relem in $rest) {
$return_list[] = $elem.$relem;
}
}
return $return_list;
}
add the ending condition (null $group_rest
) and you are set:
perms($my_arr) {
$group1 = head($my_arr);
$group_rest = tail($my_arr);
if (length($group_rest) == 0)
$rest = array();
else
$rest = perms($group_rest);
$return_list = array();
foreach($elem in $group1) {
foreach($relem in $rest) {
$return_list[] = $elem.$relem;
}
}
return $return_list;
}