Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
After seeing the following puzzle floating around the net, I decided to automate it:
Take the digits 9, 8, 7, 6, 5, 4, 3, 2, 1 in that order. Insert one or more basic math operators (addition, subtraction, division, multiplication) so that the result makes 2006.
#!/usr/bin/perl use strict; use warnings; my @o = (" + ", " - ", " * ", " / ", ""); my @s = (" ", "-"); my @d = (0, 1 .. 9); my $year = @ARGV ? shift : 2006; for my $o8 (@o) { for my $o7 (@o) { for my $o6 (@o) { for my $o5 (@o) { for my $o4 (@o) { for my $o3 (@o) { for my $o2 (@o) { for my $o1 (@o) { for my $s (@s) { my $expr = "$s$d[9]$o8$d[8]$o7$d[7]$o6$d[6]$o5" . "$d[5]$o4$d[4]$o3$d[3]$o2$d[2]$o1$d[1]"; print "$expr == $year\n" if $year == eval $expr; }}}}}}}}} __END__ 2006 == -9 + 8 * 7 + 654 * 3 - 2 - 1 2006 == 9 + 8 * 7 + 654 * 3 - 21 2006 == 9 + 8 * 7 * 6 * 5 - 4 + 321 2006 == 9 * 8 - 7 + 654 * 3 - 21
I'm sure there are cleverer ways of writing the nested loop, using some kind of module. But cut-and-paste is fast, and this takes less programmer time.
Perl --((8:>*

In reply to Happy 2006 by Perl Mouse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-20 00:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found