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.
It doesn't matter whether the multiplication is evaluated left-to-right or right-to-left, because multiplication is associative. The product is the same either way. > Anyhow, here's the little program I whipped up for it... the fun part is > that it is one of the rare times that counting base-3 is useful: > > for (my $count = 0; $count < 3**8; $count += 1) > { my $try = fixstr($count) ; > print $try,"\n" if eval($try) == 2002 ; > } > exit ; > > sub fixstr > { my $key = $_[0] ; > my $str = "123456789" ; > for (my $i = 8; $i > 0; $i -= 1) > { my $next = $key % 3 ; > $key = int($key/3) ; > next unless $next ; > substr ($str, $i, 0, $next == 1? '+': "*") ; > } > return $str ; > } > > Obviously I'm not a golfer, but I'm wondering if there are any other > interesting approaches to the problem... [base-3 and eval seemed pretty > clean/cute to me] There was discussion of this puzzle on the Boston.pm mailing list as well. The thread starts at http://mail.pm.org/pipermail/boston-pm/2002-October/000160.html Ronald