... you write a program to solve a recent Car Talk puzzler which describes a sequence of (partial) palindromic odometer readings which occur at intervals one mile (kilometer) apart.
Then again, you might merely <3 Perl.
#!/usr/bin/perl
## ~/bin/odometer_pal - find
########################################################################
## Given: six digit odometer which reads integral units (represented
## here in the form a|b|c|d|e|f ). A driver observes the following
## sequence...
##
## T(0): Last four digits form a palindrome, i.e. ?|?|c|d|e|f ::
## cdef == fedc
##
## One mile later, odometer now displays a value such that
## T(1): Last five digits are palindromic, i.e. ?|b|c|d|e|f ::
## bcdef == fedcb
## && ((bcdef-1) - (fedbc-1))%100000 == 0
##
## One mile later, odometer now displays a value such that
## T(2): Middle four digits palindromic, i.e. ?|b|c|d|e|? ::
## bcde == edcb
##
## One mile later, odometer now displays a value such that
## T(3): All six digits palindromic, i.e. a|b|c|d|e|f ::
## abc == fed
##
## Question: what was the original odometer reading at T(0)?
########################################################################
use strict;
## ary2int() - Convert array of digits to integer value.
sub ary2int {
my $val = 0;
foreach (@_) {
$val *= 10;
$val += $_;
}
return $val;
}
## int2ary() - Convert integer value ( <= 999999) to array of digits.
sub int2ary {
my $strval = sprintf "%06d", @_[0];
my @ary = split //, $strval;
return @ary;
}
#
# Start with last assertion first, then work backwards to derive
# viable candidates. Condition << abcdef == fedcba >> limits
# possible combinations to only 1000.
#
for (my $a = 0; $a <= 9; $a++) {
my $odo3 = 100001 * $a;
for (my $b = 0; $b <= 9; $b++) {
my $odo3 = $odo3 + 10010 * $b;
for (my $c = 0; $c <= 9; $c++) {
my $odo3 = $odo3 + 1100 * $c;
# $odo3 is a six-digit palindrome by construction
# Apply third criterion -- middle four digits are palindromic
my @odo2 = int2ary($odo3 - 1);
next unless $odo2[1] == $odo2[4];
next unless $odo2[2] == $odo2[3];
my $odo2 = ary2int(@odo2); # back to integer
# Apply second criterion -- last five digits are palindromic
my @odo1 = int2ary($odo2 - 1);
next unless $odo1[1] == $odo1[5];
next unless $odo1[2] == $odo1[4];
my $odo1 = ary2int(@odo1); # back to integer
# Apply first criterion -- last four digits are palindromic
my @odo0 = int2ary($odo1 - 1);
next unless $odo0[2] == $odo0[5];
next unless $odo0[3] == $odo0[4];
my $odo0 = ary2int(@odo0); # back to integer
# Still here? OK, you are a winner!
print "Solution: $odo0\n";
}
}
}
__END__
2008-01-20
You might be a geek if...
Maundered by
CJH / esper
at
04:13
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment