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