Last active
July 19, 2016 23:16
-
-
Save pjf/95b0d5e5aa0d44c67d1f54b590900b69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl -w | |
use 5.010; | |
use strict; | |
use warnings; | |
use autodie; | |
# In Perl, regular expressions can REFER TO THEMSELVES. | |
# Yes, this is both awesome and dangerous. | |
# | |
# However this isn't *fast*, it's mainly done to show that | |
# you can. | |
my $pallindrome; | |
$pallindrome = qr{ # A pallindrome is... | |
. # A single character | |
| # OR... | |
# Nothing at all | |
| # OR... | |
(.) (??{ $pallindrome }) \1 # The same character on either side of a pallindrome. | |
}x; | |
# Use three-digit ('100'..'999') by default, but | |
# accept a cmdline argument that allows for more. | |
# Eg: `pallindrome 4` | |
my ($digit_length) = $ARGV[0] || 3; | |
my $min = '1' . ('0' x ($digit_length - 1)); # Eg: 100 | |
my $max = '9' x $digit_length; # Eg: 999 | |
my $best_pallindrome = 0; | |
foreach my $x ($min..$max) { | |
foreach my $y ($min..$max) { | |
my $candidate = $x * $y; | |
if ($candidate > $best_pallindrome and $candidate =~ /^$pallindrome$/) { | |
say "New candidate: $candidate ($x × $y)"; | |
$best_pallindrome = $candidate; | |
} | |
} | |
} | |
say "The longest pallindrome is $best_pallindrome"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment