When I run
use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 0;
my @x = (1,2,3,4);
my @y = find_all_subsets(@x);
foreach my $subset (@y) {
print Dumper($subset), "\n";
}
(+ the original script) the output is
[1]
[1,4]
[1,3]
[1,3,4]
[1,2]
[1,2,4]
[1,2,3]
[1,2,3,4]
[2]
[2,4]
[2,3]
[2,3,4]
[3]
[3,4]
[4]
Please note the [ ] in the output, we'll come back to them later.
function find_all_subsets (array $x) {
if ( 1>= count($x) ) { // the >= differs from the original script, use == or === if you want to keep it "more original"
return array($x);
}
else {
$all_subsets = array();
$last_item = array_pop($x);
$first_subsets = find_all_subsets($x) ;
foreach ($first_subsets as $subset) {
array_push($all_subsets, $subset);
array_push($subset, $last_item);
array_push($all_subsets, $subset);
}
array_push ($all_subsets, array($last_item));
return $all_subsets;
}
}
$x = array(1,2,3,4);
$y = find_all_subsets($x);
foreach($y as $subset) {
echo '(', join(',', $subset), ")\n";
}
produces
(1)
(1,4)
(1,3)
(1,3,4)
(1,2)
(1,2,4)
(1,2,3)
(1,2,3,4)
(2)
(2,4)
(2,3)
(2,3,4)
(3)
(3,4)
(4)
so far so good. Now back to the [ ]. Data::Dumper chose this [ ] and not ( ) beacuse it's not an array but an array-reference (bare me if I don't use the correct terms; perl is really not my strong suit). Let's change the perl test script and look at the effect all those reference thingies have.
use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 0;
$x2 = 2;
my @x = (1,\$x2,3,4);
my @y = find_all_subsets(@x);
$x2 = 99;
foreach my $subset (@y) {
print Dumper($subset), "\n";
}
and the output changes to
[1]
[1,4]
[1,3]
[1,3,4]
[1,\99]
[1,\99,4]
[1,\99,3]
[1,\99,3,4]
[\99]
[\99,4]
[\99,3]
[\99,3,4]
[3]
[3,4]
[4]
You see, I change $x2 after the call to find_all_subsets() but still in the result the new value is used and Data::Dumper marks the "value" as a reference ( \99 instead of simply 99 ). Do you need this feature in your php script, too?