Chris Spurgeon wrote:

> I was asked to figure out all of the different ways you can add up various
> combinations of the digits 1 through 9 to create different totals. For
> instance, you can get 8 by adding 1+7 or 2+5 or 3+4 or 1+2+4 (for each
> addition, each numeral can only be used once.)  I wrote this code to
> generate all of the values, but as you can see I resorted to doing it by
> first figuring out all of the 2-digit combinations, and then all of the
> 3-digit combinations, ...all the way up to nine.  It strikes me that this
> could have been more elegantly done with some sort of recursive function,
> but I couldn't figure out how.  Any ideas?

First of all don't use C-style for loops when you want to iterate
through a range of integers. Instead:

  for ($i = 1; $i <= 9; $i++ ) { some_code }

you can use just:

  for $i (1..9) { some_code }

It would extremely simplify such code like yours.

And now, my suggestion:

----8<--------8<----
#!/usr/bin/perl -w

my $max=9;

numbers($max+1);
sub numbers{
    my $d=shift;
    if(--$d){ numbers($d,@_,$_) for (0,$d) }
    else{ printsum(@_) }
}
sub printsum{
    my $s;
    $s+=$_ for @_;
    print join('+',@_),"=$s\n";
}
----8<--------8<----

It's recursive and more elegant, for some definition of elegance. :)
Tell me if that's what you need and what do you want me to explain.
I optimized it for typing time, not readability. Change $max to any
number you want, but more than 40 can take centuries, so prepare for
waiting. ;)

> Thanks in advance, one and all,
> here's my original code....
> (...)

You should consider participating in Obfuscated Perl Contest. :)

- RaFaL Pocztarski, [EMAIL PROTECTED]

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to