Re: [QUIZ] Perl 'Medium' Quiz of the Whatever #2008-02-28 - Kakuro Digit Sums

[email protected] Thu, 06 Mar 2008 23:05:11 +1300
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
Shlomi Fish writes:
>IMPORTANT: Please do not post solutions, hints, or other spoilers
>until at least 60 hours after the date of this message.  Thanks.
>
>Kakuro (a.k.a Cross-sums) is a kind of puzzle game:

Here's my solution.  It, too, is recursive, but unlike M. Fish's, I've
used a secondary accumulator parameter.

    -- michael.

--
#!perl
use strict;
sub get_digits_sum {
    my ($sum, $left, $soln, @ns) = @_;
    return 
	if $sum == 0;
    return [get_digits_sum($sum, $left, [], 1..9)] 
	if !defined $soln;
    return (grep {$sum==$_} @ns) ? [@$soln, $sum] : () 
	if $left == 1;
    my @rv;
    for my $n (@ns) {
	return @rv 
	    if $n > $sum; # rest won't work either
	push @rv, get_digits_sum($sum-$n, $left-1, [@$soln, $n], ($n+1)..9);
    }
    return @rv;
}
my ($sum, $places) = @ARGV;
my $rv = get_digits_sum($sum, $places);
print join " ", @$_, "\n" for @$rv;