diff options
| author | Niels van Dijke <perlboy@cpan.org> | 2024-09-30 08:11:30 +0000 |
|---|---|---|
| committer | Niels van Dijke <perlboy@cpan.org> | 2024-09-30 08:11:30 +0000 |
| commit | f5953e315fe4ad666cfb5a903dc3fa2b5ce704ee (patch) | |
| tree | 1c8ffb6e2408261d24202f32b4ca518820e3f76d | |
| parent | 5bfb306153546664c3549d2aafab5a2bed4b1c88 (diff) | |
| download | perlweeklychallenge-club-f5953e315fe4ad666cfb5a903dc3fa2b5ce704ee.tar.gz perlweeklychallenge-club-f5953e315fe4ad666cfb5a903dc3fa2b5ce704ee.tar.bz2 perlweeklychallenge-club-f5953e315fe4ad666cfb5a903dc3fa2b5ce704ee.zip | |
w288 - Task 1
| -rwxr-xr-x | challenge-288/perlboy1967/perl/ch1.pl | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/challenge-288/perlboy1967/perl/ch1.pl b/challenge-288/perlboy1967/perl/ch1.pl new file mode 100755 index 0000000000..5e7a7e7b64 --- /dev/null +++ b/challenge-288/perlboy1967/perl/ch1.pl @@ -0,0 +1,47 @@ +#!/bin/perl + +=pod + +L<https://theweeklychallenge.org/blog/perl-weekly-challenge-288#TASK1> + +Author: Niels 'PerlBoy' van Dijke + +Task 1: Closest Palindrome +Submitted by: Mohammad Sajid Anwar + +You are given a string, $str, which is an integer. + +Write a script to find out the closest palindrome, not including itself. +If there are more than one then return the smallest. + +|| The closest is defined as the absolute difference minimized between two integers. + +=cut + +use v5.32; +use feature qw(signatures); +no warnings qw(experimental::signatures); +use common::sense; + +use Test2::V0 qw(-no_srand); + +use List::Util qw(min); + +sub closestPalindrome ($int) { + my @p = ($int-1,$int+1); my @d = (-1,+1); + + for (0,1) { + $p[$_] += $d[$_] while ($p[$_] > 0 and $p[$_] ne reverse $p[$_]); + } + + my $minDelta = min map { abs($int-$_) } @p; + + return [@p[grep { $p[$_] - $d[$_] * $minDelta == $int } (0,1)]]; +} + +is(closestPalindrome(123),[121]); +is(closestPalindrome(2),[1,3]); +is(closestPalindrome(1400),[1441]); +is(closestPalindrome(1001),[999]); + +done_testing; |
