Sunday, May 5, 2024

TWC268

Challenge Link

Task1

We take the absolute value of the first elements of arrays after sorting them:

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

sub magic_number{
  my @x = sort{$a <=> $b} @{$_[0]};
  my @y = sort{$a <=> $b} @{$_[1]};
  abs($x[0] - $y[0])
}

printf "%d\n",magic_number([3,7,5],[9,5,7]);
printf "%d\n",magic_number([1,2,1],[5,4,4]);
printf "%d\n",magic_number([2],[5]);

Task2

After sorting the array, we keep removing pairs of elements and push its reverse to the array that we want to return:

#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub number_game{
  my @arr = sort{$a <=> $b} @{$_[0]};
  my @ret;
  push @ret,reverse splice @arr,0,2 while(@arr);
  @ret
}

print show number_game([2,5,3,4]);
print show number_game([9,4,1,3,6,4,6,1]);
print show number_game([1,2,2,3]);

Wednesday, April 24, 2024

TWC266

Challenge Link

 Task1

We count the words in a hash, then check which one's count is equal to one, and sort them:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub uncommon_words{
  my %h;
  $h{lc $_}++ foreach split /\W+/, $_[0] . ' ' . $_[1];
  sort grep{$h{$_} == 1} keys %h;
}

print show uncommon_words('Mango is sweet','Mango is sour');
print show uncommon_words('Mango Mango','Orange');
print show uncommon_words('Mango is Mango','Orange is Orange');

Task2

In an NxN square matrix, if the indices i and j are equal then we are on the main diagonal, and if the sum of i and j is equal to N-1, then we are on the anti-diagonal, and if these conditions are true, then we shouldn't see a 0 and if we do we return 0 immediately, and if the above 2 conditions is not met, then we must see a zero since we are not on the diagonals. If the function doesn't return inside the loops then we definitely have an X matrix:
#!/usr/bin/env perl
use strict;
use warnings;

sub x_matrix{
  my ($mat) = @_;
  my $n = @$mat;
  foreach my $i(0..$n-1){
    foreach my $j(0..$n-1){
      if($i == $j || $i+$j == $n-1){
	return 0 if $mat->[$i][$j] == 0
      }
      elsif($mat->[$i][$j] != 0){return 0}
    }
  }
  1
}

printf "%d\n",x_matrix([[1,0,0,2],
			[0,3,4,0],
			[0,5,6,0],
			[7,0,0,1]]);

printf "%d\n",x_matrix([[1,2,3],
			[4,5,6],
			[7,8,9]]);

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

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

Tuesday, April 9, 2024

TWC264

Challenge Link

Task1

We make two sets of lowercase and uppercase letters and find their intersection:
#!/usr/local/bin/env perl
use strict;
use warnings;
use Set::Scalar;
use List::Util qw(maxstr);

sub greatest_english_letter{
  my $s1 = Set::Scalar->new;
  my $s2 = Set::Scalar->new;
  map{$_ le 'Z' ? $s1->insert($_) : $s2->insert(uc $_)} split '',$_[0];
  maxstr($s1->intersection($s2)->members) // ''
}

printf "%s\n", greatest_english_letter('PeRlwEeKLy');
printf "%s\n", greatest_english_letter('ChaLlenge');
printf "%s\n", greatest_english_letter('The');

Task2

We insert the elements at appropriate indices as per the given instructions:

#!/usr/local/bin/env perl
use strict;
use warnings;
use Data::Show;

sub target_array{
  my @ret;
  splice @ret,$_[1]->[$_],0,$_[0]->[$_] foreach(0..$#{$_[1]});
  @ret
}

print show target_array([0,1,2,3,4],[0,1,2,2,1]);
print show target_array([1,2,3,4,0],[0,1,2,3,0]);
print show target_array([1],[0]);

Monday, April 1, 2024

TWC263

Challenge Link

Task1

We sort the array then return the indices of the elements equal to k:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub target_index{
  my @sorted = sort{$a <=> $b} @{$_[0]};
  map{$sorted[$_] == $_[1] ? $_ : ()}0..$#{$_[0]};
}

print show target_index([1,5,3,2,4,2],2);
print show target_index([1,2,4,3,5],6);
print show target_index([5,3,2,4,2,1],4);

Task2

We add each quantity to the count of ids in the hash and return the keys and values of the hash:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub merge_items{
  my %h;
  $h{$_->[0]} += $_->[1] foreach(@{$_[0]},@{$_[1]});
  map{[$_,$h{$_}]} sort{$a <=> $b} keys %h;
}

print show merge_items([[1,1],[2,1],[3,2]],[[2,2],[1,3]]);
print show merge_items([[1,2],[2,3],[1,3],[3,2]],[[3,1],[1,3]]);
print show merge_items([[1,1],[2,2],[3,3]],[[2,3],[2,4]]);

Saturday, March 30, 2024

TWC262

Challenge Link

Task1

We count the number of negative and positive numbers in the array and return the maximum:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);

sub max_positive_negative{
  my ($neg,$pos) = 0 x 2;
  map{$neg++ if $_ < 0;$pos++ if $_ > 0}@{$_[0]};
  max $neg,$pos
}

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

Task2

For each (i,j) pair we check if the condition (i * j mod k == 0) holds and count them:
#!/usr/bin/env perl
use strict;
use warnings;

sub count_equal_divisible{
  my ($arr,$k) = @_;
  my $count = 0;
  foreach my $i(0..@$arr-2){
    foreach my $j($i+1..@$arr-1){
      ++$count if $arr->[$i] == $arr->[$j] && ($i*$j) % $k == 0
    }
  }
  $count
}

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

Sunday, March 17, 2024

TWC261

Challenge Link

Task1

We subtract the sum of each digit in each number from the sum of the numbers and take its absolute value:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);

sub element_digit_sum{
  abs(sum0(map{split ''}@{$_[0]}) - sum0(@{$_[0]}))
}

printf "%d\n",element_digit_sum([1,2,3,45]);
printf "%d\n",element_digit_sum([1,12,3]);
printf "%d\n",element_digit_sum([1,2,3,4]);
printf "%d\n",element_digit_sum([236,416,336,350]);

Task2

While $start is in the list, we keep multiplying it by 2:

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

sub multiply_by_two{
  my ($arr,$start) = @_;
  $start *= 2 while((firstidx{$start == $_}@$arr)!=-1);
  $start
}

printf "%d\n",multiply_by_two([5,3,6,1,12],3);
printf "%d\n",multiply_by_two([1,2,4,3],1);
printf "%d\n",multiply_by_two([5,6,7],2);

Sunday, March 10, 2024

TWC260

Challenge Link

Task1

We count the occurrences of each integer in a hash, then check if the length of the values of that hash is equal to the length of the unique values,  if so we return 1 else 0:

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

sub unique_occurences{
  my %h;
  $h{$_}++ foreach @{$_[0]};
  my @values = values %h;
  @values == (uniq @values) || 0
}

printf "%d\n",unique_occurences([1,2,2,1,1,3]);
printf "%d\n",unique_occurences([1,2,3]);
printf "%d\n",unique_occurences([-2,0,1,-2,1,1,0,1,-2,9]);

Task2

We construct an array of all permutations of the given string, join each tuple to a string, and remove the duplicates, then sort and find the index of the string which is equal to the argument of the subroutine:
#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(permutations);
use List::MoreUtils qw(onlyidx uniq);

sub dictionary_rank{
  1+onlyidx{$_ eq $_[0]}
    sort{$a cmp $b}
    uniq map{join'',@$_}
    permutations([split '',$_[0]])
}

printf "%d\n",dictionary_rank('CAT');
printf "%d\n",dictionary_rank('GOOGLE');
printf "%d\n",dictionary_rank('SECRET');

Sunday, February 25, 2024

TWC258

 Challenge Link

Task1

we split the number into its digits and check if it is even:
#!/usr/bin/env perl
use strict;
use warnings;

sub count_even_digits_number{
  scalar grep{(split'',$_)%2==0}@{$_[0]}
}

printf "%d\n",count_even_digits_number([10,1,111,24,1000]);
printf "%d\n",count_even_digits_number([111,1,11111]);
printf "%d\n",count_even_digits_number([2,8,1024,256]);

Task2

We get the popcount of each index and if it is equal to $k, we include the number at that index in the resultant array, else we skip it:
#!/usr/bin/env perl
use strict;
use warnings;
use ntheory qw(hammingweight);
use List::Util qw(sum0);

sub sum_of_values{
  sum0 map{hammingweight$_==$_[1]?$_[0]->[$_]:()}0..$#{$_[0]}
}

printf "%d\n",sum_of_values([2,5,9,11,3],1);
printf "%d\n",sum_of_values([2,5,9,11,3],2);
printf "%d\n",sum_of_values([2,5,9,11,3],0);

Sunday, February 11, 2024

TWC256

Challenge Link

Task1

We check each string with the reverse of all others and increment the count if they are equal:


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

sub maximum_pairs{
  my ($a) = @_;
  my $c = 0;
  map{my $i = $_;
      map{$c++ if $a->[$i] eq reverse $a->[$_]}$i+1..$#$a}0..$#$a;
  $c
}

printf "%d\n", maximum_pairs(['ab','de','ed','bc']);
printf "%d\n", maximum_pairs(['aa','ba','cd','ed']);
printf "%d\n", maximum_pairs(['uv','qp','st','vu','mn','pq']);

Task2

We keep picking a character from each string alternatively until we exhaust the strings:



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

sub merge_strings{
  my ($res,$m,$n) = ('',length $_[0],length $_[1]);
  for(my $i = 0; $i < $m || $i < $n; ++$i){
    $res .= substr $_[0],$i,1 if $i < $m;
    $res .= substr $_[1],$i,1 if $i < $n;
  }
  $res
}

printf "%s\n",merge_strings('abcd','1234');
printf "%s\n",merge_strings('abc','12345');
printf "%s\n",merge_strings('abcde','123');

Monday, February 5, 2024

TWC255

Challenge Link

Task1

We count the characters' occurrences of the first string, and do the same thing for the second string too but this time we decrement the count or if we hit 0 (false), then we delete that hash entry, leaving us with the only odd character as the remaining key to be returned:

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

sub odd_character{
  my %h;
  map{++$h{$_}}split '',$_[0];
  map{--$h{$_}||delete $h{$_}}split '',$_[1];
  keys %h
}

printf "%s\n",odd_character("Perl","Preel");
printf "%s\n",odd_character("Weekly","Weeakly");
printf "%s\n",odd_character("Box","Boxy");

Task2

We count the occurrences of each word excluding the banned word, and return the one with the highest count:

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

sub most_frequent_word{
  my %h;
  map{$h{$_}++ if $_ ne $_[1]} split /[^\w]/,$_[0];
  (sort{$h{$b}<=>$h{$a}}keys %h)[0]
}

printf "%s\n",most_frequent_word("Joe hit a ball, the hit ball ".
				 "flew far after it was hit.",
				 "hit");
printf "%s\n",most_frequent_word("Perl and Raku belong to the same family.".
				 " Perl is the most popular language ".
				 "in the weekly challenge.",
				 "the");

Friday, February 2, 2024

TWC254

Challenge Link

Task1

First one is a math trick that we use to find out if a number is a power of 3 or not:

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

sub three_power{
  $_[0] == int($_[0]**(1/3))**3
}

printf "%d\n",three_power(27);
printf "%d\n",three_power(0);
printf "%d\n",three_power(6);

Task2

We reverse the list of vowels and replace them in the string, and capitalize the first letter:

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

sub reverse_vowels{
  my ($str) = @_;
  my @vowels = $str =~ /[aeiou]/gi;
  $str =~ s/([aeiou])/pop @vowels/egi;
  ucfirst $str
}

printf "%s\n",reverse_vowels('Raku');
printf "%s\n",reverse_vowels('Perl');
printf "%s\n",reverse_vowels('Julia');
printf "%s\n",reverse_vowels('Uiua');

Sunday, January 28, 2024

TWC253

Challenge Link

Task1

We apply split on each element of the array then filter those which are of length > 0:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub split_strings{
  my ($arr,$sep) = @_;
  grep {length} map{split /\Q$sep\E/} @$arr
}

print show split_strings(['one.two.three','four.five','six'],'.');
print show split_strings(['$perl$$', '$$raku$'],'$');

Task2

We sort the indices according to the sum of each subarray in the matrix, or in case of them being equal, on the indices themselves:

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

sub weakest_row{
  my ($mat) = @_;
  sort{sum0(@{$$mat[$a]}) <=> sum0(@{$$mat[$b]}) || $a <=> $b}
    0..$#$mat
}

print show weakest_row([[1,1,0,0,0],
			[1,1,1,1,0],
			[1,0,0,0,0],
			[1,1,0,0,0],
			[1,1,1,1,1]]);
print show weakest_row([[1,0,0,0],
			[1,1,1,1],
			[1,0,0,0],
			[1,0,0,0]]);

Sunday, January 21, 2024

TWC252

Challenge Link

Task1

We check if the array's length is divisible by index+1, if so we square the array at that index, at last we sum the whole acquired array:

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

sub special_numbers{
  my ($arr) = @_;
  sum0 map{($arr->[$_] ** 2) if @$arr % ($_+1) == 0} 0..$#$arr;
}

printf "%d\n",special_numbers([1,2,3,4]);
printf "%d\n",special_numbers([2,7,1,19,18,3]);

Task2

Starting from 1 to the half of the given number, we keep pushing the number and its negation to an array, then if the given number is odd, we push an extra zero at the end:

#!usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub unique_sum_zero{
  my ($n,@ret) = @_;
  foreach(1..$n/2){
    push(@ret,$_,-$_);
  }
  $n % 2 ? (@ret,0) : @ret;
}

print show unique_sum_zero(5);
print show unique_sum_zero(3);
print show unique_sum_zero(1);

Monday, January 1, 2024

TWC250

Challenge Link

Task1

We iterate the array, and if the result of index mod 10 is equal to the array's element at that index, we return that index, otherwise we return -1:

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

sub smallest_index{
  map{return $_ if $_ % 10 == $_[0]->[$_]}0..$#{$_[0]};
  -1
}

printf "%d\n",smallest_index([0,1,2]);
printf "%d\n",smallest_index([4,3,2,1]);
printf "%d\n",smallest_index([1,2,3,4,5,6,7,8,9,0]);

Task2

We iterate the array, if the element is numeric, we use it, else we get the length of the string and assign it to $n, then get the max of array:

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

sub alphanumeric_string_value{
  max map{my $n = (/^\d+$/) ? $_ : length}@{$_[0]};
}

printf "%d\n",alphanumeric_string_value(['perl','2','000','python','r4ku']);
printf "%d\n",alphanumeric_string_value(['001','1','000','0001']);