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');

No comments:

Post a Comment