Front page | perl.fwp | Postings from October 2002

## NPL Puzzler for 6 Oct

Thread Next
From:
Bernie Cosell
Date:
October 11, 2002 11:54
Subject:
NPL Puzzler for 6 Oct
Message ID:
200210111854.g9BIsNY11732@mail.rev.net
```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.

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]

/Bernie\

--
Bernie Cosell                     Fantasy Farm Fibers
mailto:bernie@fantasyfarm.com     Pearisburg, VA
-->  Too many people, too few sheep  <--

```
Thread Next

nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About