Skip to content

Instantly share code, notes, and snippets.

@pjf
Last active July 19, 2016 23:16
Show Gist options
  • Save pjf/95b0d5e5aa0d44c67d1f54b590900b69 to your computer and use it in GitHub Desktop.
Save pjf/95b0d5e5aa0d44c67d1f54b590900b69 to your computer and use it in GitHub Desktop.
#!/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