Monday, April 15, 2024

TWC265

Challenge Link

Task1

We see if the element count of an item is greater than or equal to 33% of the whole array size:


#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min);

sub thirty_three_percent_appearance{
  my %h;
  $h{$_}++ foreach @{$_[0]};
  min grep{$h{$_} if $h{$_} >= (@{$_[0]}/3)}keys %h;
}

printf "%d\n",thirty_three_percent_appearance([1,2,3,3,3,3,4,2]);
printf "%d\n",thirty_three_percent_appearance([1,1]);
printf "%d\n",thirty_three_percent_appearance([1,2,3]);

Task2

We check if the given string is a subset of any of the given strings in the array:

#!/usr/bin/env perl
use strict;
use warnings;
use Set::Scalar;

sub completing_word{
  my $s1 = Set::Scalar->new(split'',(lc $_[0] =~ s/(\s+|\d+)//gr));
  (grep{$_ if $s1 <= (Set::Scalar->new(split'',$_))}@{$_[1]})[0];
}

printf "%s\n",completing_word('aBc 11c',['accbbb','abc','abbc']);
printf "%s\n",completing_word('Da2 abc',['abcm','baacd','abaadc']);
printf "%s\n",completing_word('JB 007',['jj','bb','bjb']);

No comments:

Post a Comment