J
Jeffrey
Hi everyone,
I'm looking for a way to pass a number into a subroutine, and have it
give back a list of all the ways that number can been added to get to
that number.
For example, if the function were to take 3 as a parameter it would
give me back:
1,1,1
2,1
3
for 5 it would give back:
1,1,1,1,1
2,2,1
3,2
3,1,1
4,1
5
2,1,1,1
I haven't been able to come up with anything that does this the way I
want:
So far I did:
&Sum(3)
sub Sum {
my $sum = shift;
for (my $i=0; $i<=$sum; $i++) {
for (my $j=0; $j<=$sum; $j++) {
for (my $k=0; $k<=$sum; $k++) {
if ($i+$j+$k == $sum) {
print "[$i, $j, $k] \n";
}
}
}
}
}
But, that is hard-coded for $sum=3, it can't work with anything else.
Also I would consider 0,0,3 to be the same as 0,3,0 and 3,0,0.
Thanks for any ideas,
Jeffrey
I'm looking for a way to pass a number into a subroutine, and have it
give back a list of all the ways that number can been added to get to
that number.
For example, if the function were to take 3 as a parameter it would
give me back:
1,1,1
2,1
3
for 5 it would give back:
1,1,1,1,1
2,2,1
3,2
3,1,1
4,1
5
2,1,1,1
I haven't been able to come up with anything that does this the way I
want:
So far I did:
&Sum(3)
sub Sum {
my $sum = shift;
for (my $i=0; $i<=$sum; $i++) {
for (my $j=0; $j<=$sum; $j++) {
for (my $k=0; $k<=$sum; $k++) {
if ($i+$j+$k == $sum) {
print "[$i, $j, $k] \n";
}
}
}
}
}
But, that is hard-coded for $sum=3, it can't work with anything else.
Also I would consider 0,0,3 to be the same as 0,3,0 and 3,0,0.
Thanks for any ideas,
Jeffrey