Friday, June 14, 2024

TWC273

Challenge Link

Task1

We count the character's occurrences and calculate its percentage:

#!/usr/bin/env perl
use strict;
use warnings;
use POSIX qw(round);

sub percentage_of_character{
  my ($str,$char) = @_;
  my $count =()= $str =~ /\Q$char/g;
  round(100 * $count / length $str)
}

printf "%d\n",percentage_of_character('perl','e');
printf "%d\n",percentage_of_character('java','a');
printf "%d\n",percentage_of_character('python','m');
printf "%d\n",percentage_of_character('ada','a');
printf "%d\n",percentage_of_character('ballerina','l');
printf "%d\n",percentage_of_character('analitik','k');

Task2

We see if there's no 'a' character after the last 'b' character:

#!/usr/bin/env perl
use strict;
use warnings;

sub b_after_a{
  (-1 != index($_[0],'b')) >= rindex($_[0],'a')
}

printf "%d\n",b_after_a('aabb');
printf "%d\n",b_after_a('abab');
printf "%d\n",b_after_a('aaa');
printf "%d\n",b_after_a('bbb');

Sunday, June 2, 2024

TWC272

Challenge Link

Task1

Replacing each . with [.]:
#!/usr/bin/env perl
use strict;
use warnings;

sub defrag_ip_address{
  $_[0] =~ s/\./[.]/gr
}

printf "%s\n",defrag_ip_address('1.1.1.1');
printf "%s\n",defrag_ip_address('255.101.1.0');

Task2

Subtracting the absolute values of pairs and taking their sum:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);
use List::MoreUtils qw(slide);

sub string_score{
  sum0 slide {abs(ord($b) - ord($a))} split '',$_[0]
}

printf "%d\n",string_score('hello');
printf "%d\n",string_score('perl');
printf "%d\n",string_score('raku');