On Fri, Oct 11, 2002 at 02:54:20PM -0400, Bernie Cosell wrote:
> The NPL puzzle for 6 oct was an interesting little Perl exercise [I'm not
> sure how to solve it analytically --- I played with it some to little
> avail --- but it was certainly subject to brute force, and it turned out
> to be a cute little thing.
>
> Write out the digits from 1-9 in order. Then add some plus (+) signs
> and times (x) signs to the string to make it add up to 2,002. As
> usual in arithmetic, multiplication is done before addition, and you
> don't have to put a sign between every 2 digits. The answer is
> unique.
>
> What's odd is that my little Perl program found *TWO* solutions, but one
> is potentially ambiguous [in particular, given those rules, what should
> the value of "a*b*c" be?-- it doesn't say whether things should be done
> left-to-right or right-to-left, so perhaps that could be used to exclude
> one of the two solutions.
I too get two solutions, and if one is ambiguous due to a * b * c, the
other is too, due to a + b + c. I'm not using base-3 counting, but I'm
using recursion:
#!/usr/bin/perl
use strict;
use warnings;
my $target = @ARGV ? shift : 2002;
my @digits = 1 .. 9;
my @op = ("", " + ", " * ");
sub doit;
sub doit {
my ($str, @digits) = @_;
unless (@digits) {
my $result = eval $str;
print "$str == $target\n" if $target == eval $str;
return;
}
my $digit = shift @digits;
doit "$str$_$digit" => @digits foreach @op;
}
doit @digits;
__END__
1 * 23 + 45 * 6 * 7 + 89 == 2002
1 * 2 + 34 * 56 + 7 + 89 == 2002
Here's the complete set of solutions for this century:
1 * 23 + 45 * 6 * 7 + 89 == 2002
1 * 2 + 34 * 56 + 7 + 89 == 2002
12 + 34 * 56 + 78 + 9 == 2003
12 + 3 * 456 + 7 * 89 == 2003
1 + 23 + 45 * 6 * 7 + 89 == 2003
1 + 2 + 34 * 56 + 7 + 89 == 2003
12 + 34 * 56 + 7 + 89 == 2012
12 * 3 + 45 * 6 * 7 + 89 == 2015
123 + 45 * 6 * 7 + 8 + 9 == 2030
1234 + 5 + 6 + 789 == 2034
1 * 2 * 3 * 4 * 56 + 78 * 9 == 2046
1 + 2 * 3 * 4 * 56 + 78 * 9 == 2047
1234 + 5 * 6 + 789 == 2053
1 * 2 * 34 * 5 * 6 + 7 + 8 + 9 == 2064
1 + 2 * 34 * 5 * 6 + 7 + 8 + 9 == 2065
12 * 34 * 5 + 6 + 7 + 8 + 9 == 2070
1 * 2 + 3 * 456 + 78 * 9 == 2072
1 + 2 + 3 * 456 + 78 * 9 == 2073
1234 + 56 + 789 == 2079
12 + 3 * 456 + 78 * 9 == 2082
123 + 45 * 6 * 7 + 8 * 9 == 2085
1 * 2 + 345 * 6 + 7 + 8 + 9 == 2096
12 * 34 + 5 * 6 * 7 * 8 + 9 == 2097
12 * 3 * 45 + 6 * 78 + 9 == 2097
1 + 2 + 345 * 6 + 7 + 8 + 9 == 2097
12 * 34 * 5 + 6 * 7 + 8 + 9 == 2099
The 2034 and 2079 solutions use only additions and concatination.
Abigail