Advent Calendar 2021
| Day 8 | Day 9 | Day 10 |
The gift is presented by Laurent Rosenfeld. Today he is talking about his solution to “The Weekly Challenge - 114”. This is re-produced for Advent Calendar 2021 from the original post by Laurent Rosenfeld
.
Task #1: Next Palindrome Number
You are given a positive integer $N
.
Write a script to find out the next Palindrome Number
higher than the given integer $N
.
Next Palindrome Number in Raku
In theory, we could build directly the next palindrome number from the current one. But there are different situations to cover, depending for example on whether the input number has an odd or even number of digits. Also, there are various edge cases. It is not so easy to be sure you’ve covered all possible cases. The alternative is to check each number in ascending order until you get a match. This brute force approach is much easier and in fact quite efficient for small and moderately large input numbers, as it is in most cases quite fast to find a palindrome larger than a given input number. We’ll use this second approach. We assume here that the input is a correct integer.
use v6;
my $input = @*ARGS[0] // 1234;
for $input .. Inf -> $candidate {
next unless $candidate eq $candidate.flip;
say $candidate;
last;
}
This program displays the following output:
$ raku ./palin.raku
1331
$ raku ./palin.raku 3445
3553
Next Palindrome Number in Perl
We use the same algorithm, except that we use a while
loop instead of a for
because it is not possible to define an infinite range in Perl.
use strict;
use warnings;
use feature "say";
my $num = shift // 1234;
$num =~ s/^0+//; # remove leading 0s just in case
while (++ $num) {
say $num and last if $num eq reverse $num;
}
This program displays the following output:
$ perl palin.pl
1331
$ perl palin.pl 3554
3663
$ perl palin.pl 075
77
If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.