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 :-(


In reply to Re: Challenge: Nearest Palindromic Number by Corion
in thread Challenge: Nearest Palindromic Number by Limbic~Region

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.