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.
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.#!/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
Perl --((8:>*
Back to
Cool Uses for Perl