Perl Weekly Challenge 359: quick and dirty!
This post presents my solutions to the Perl Weekly Challenge 359.I keep doing the Perl Weekly Challenge in order to mantain my coding skills in good shape, as well as in order to learn new things, with particular regard to Raku, a language that I love.
This week, I solved the following tasks:
- PWC 359 - Task 1 - Raku
- PWC 359 - Task 2 - Raku
- PWC 359 - Task 1 in PostgreSQL PL/Perl
- PWC 359 - Task 2 in PostgreSQL PL/Perl
Raku Implementations
PWC 359 - Task 1 - Raku Implementation
Given a number, compute the number of time the digits have to be summed to get a single digit number and what this number is.sub MAIN( Int $number ) {
my $persistence = 0;
my $root = $number;
while ( $root >= 10 ) {
$root = [+] $root.Str.comb.map( *.Int );
$persistence++;
}
"Persistence : $persistence \nRoot : $root".say;
}
PWC 359 - Task 2 - Raku Implementation
Given a string, remove all adiacent duplicated characters.sub MAIN( Str $string where { $string ~~ / ^ <[a..zA..Z]>+ $ / } ) {
my $reduced = $string;
$reduced ~~ s:g/ (.) $0 //;
$reduced.say;
}
PL/Perl Implementations
PWC 359 - Task 1 - PL/Perl Implementation
Straightfoward with the usagesplit:
CREATE OR REPLACE FUNCTION
pwc359.task1_plperl( int )
RETURNS SETOF INT
AS $CODE$
my ( $number ) = @_;
my $root = $number;
my $persistence = 0;
while ( $root > 9 ) {
my $sum = 0;
for ( split //, $root ) {
$sum += $_;
}
$root = $sum;
$persistence++;
}
return [ $persistence, $root ];
$CODE$
LANGUAGE plperl;
PWC 359 - Task 2 - PL/Perl Implementation
Use the same regular expression approach as in Raku:CREATE OR REPLACE FUNCTION
pwc359.task2_plperl( text )
RETURNS text
AS $CODE$
my ( $string ) = @_;
$string =~ s/ (.) \1 //gx;
return $string;
$CODE$
LANGUAGE plperl;