Created
October 28, 2023 15:53
-
-
Save bradclawsie/6043f921de8ae3098dde9c2834470e44 to your computer and use it in GitHub Desktop.
palindrime.pl
This file contains hidden or 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/env perl | |
# perl note - if @ds = [1,2,3], shift(@ds) returns 1 and make @ds be [2,3] | |
# | |
# perl note - perl lets you treat chars and numbers the same and just mostly | |
# figures out what to do | |
use v5.38; | |
# the input | |
my $t = '8155999'; | |
# the output should have the highest value - that means the | |
# highest number should be the first digit | |
# | |
# turn the string into a sorted array of digits | |
# | |
# reverse/sorting it will make sure the values decrease, and | |
# since it is sorted, we know we will see all of a certain | |
# number sequentially (i.e. below, we don't see a 9 appear at | |
# the end of the array) | |
my @ds = reverse(sort(split(//,$t))); # 8155999 -> [9,9,9,8,5,5,1] | |
# prepare the output variables - | |
# $left: the "left" side of the palindrome | |
# $middle: the "center" of the palindrome (could be empty!) | |
# $right: the "right" side of the palindrome | |
# | |
# why is $middle -1? to set up for replacing it with the biggest | |
# value found | |
my ($left,$middle,$right) = ('', -1, ''); | |
# in pseudocode: | |
# while there are digits left in @ds { | |
# if there are at least two digits and they are the same { | |
# set $left to be $left . the first value | |
# set $right to be the second value . $right | |
# } else { | |
# the next number does not have a "pair", so | |
# it can either be made the $middle if it is | |
# larger than $middle (which should only happen | |
# once since the list is sorted) | |
# } | |
# } | |
# print $left . $middle . $right | |
# | |
while ($#ds != 0) { # while @ds has elements | |
if (($#ds != 1) && ($ds[0] == $ds[1])) { # matching pair | |
($left, $right) = ($left . shift(@ds), shift(@ds) . $right); | |
} else { # only occurs once | |
# because we reverse sorted the array, the first number | |
# we see hear is the best one to pick, it is the largest | |
$middle = $ds[0] if ($middle == -1); | |
shift(@ds); | |
} | |
} | |
say $left . $middle . $right; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment