My hypothesis is the following:
For a number of even length ABCDEF
there are three "close" palindromes:
AB(C-1)(C-1)BA
# ABCCBA
AB(C+1)(C+1)BA
For a number of odd length ABCDEFG
there are also three "close" palindromes:
AB(C-1)D(C-1)BA
ABCDCBA
AB(C+1)D(C+1)BA
I brute force the closest palindrome of the three:
use strict;
for my $n (1..1000000) {
#for my $n (1000..1090) {
my $candidate = palindrome($n);
print "$n: $candidate\n";
};
use strict;
sub palindrome {
my ($n) = @_;
my $l = int ((length $n) / 2);
$n =~ /^(\d{$l})(.?)(\d{$l})$/
or return $n;
my ($left,$middle,$right) = ($1,$2,$3);
my @parts = map { ($left ? $left + $_ : "") . $middle . ($left ? rev
+erse $left + $_ : "") } (-1, 0, 1);
for (@parts) {
die "$n: $_ is no palindrome"
if $_ ne reverse $_;
};
my $result = $parts[0];
for (@parts) {
$result = $_ if abs($n - $_) < abs($n - $result);
};
die "$n: $result is no palindrome"
if $result ne reverse $result;
return $result
};
Update: On thinking a bit longer about this, I think my hypothesis above is wrong, but my code is still right, as there is the case of C == 0, which I neglected to mention. My handling of the code below, still generates the good results though.
Feh. On further testing, my code already fails for 107, where the closest palindrome is 111 and not 101 as my code finds. Oh well :-(
-
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.