Sunday, December 31, 2023

TWC249

Challenge Link

Task1

We count the values in a hash, if there are any odd number counts, we return an empty array, else we pair up the elements:


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

sub equal_pairs{
  my %h;
  $h{$_}++ foreach @{$_[0]};
  (all{$_%2} values %h) ? () : map{my $k=$_;map{[$k,$k]}1..$h{$k}/2}keys %h;
}

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

Task2

We initialize two variables $i and $j to 0 and length of the string respectively, if the character in the string is equal to 'I' then we increment $i else we decrement $j, and lastly append the $i to the end of the result:

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

sub di_string_match{
  my ($i,$j) = (0,length $_[0]);
  (map{$_ eq 'I' ? $i++ : $j--}split '',$_[0]),$i;
}

print show di_string_match('IDID');
print show di_string_match('III');
print show di_string_match('DDI');

Friday, December 22, 2023

TWC248

Challenge Link

Task1

We take the distances and append them to an array:
#!/usr/bin/env perl
use strict;
use warnings;
use List::MoreUtils qw(indexes);
use List::Util qw(min);

sub shortest_distance{
  my @arr = split'',$_[0];
  map{my $i = $_; min map{abs $i - $_}indexes{$_ eq $_[1]}@arr}0..$#arr;
}

printf "(%s)\n",join ',',shortest_distance('loveleetcode','e');
printf "(%s)\n",join ',',shortest_distance('aaab','b');

Task2

We use the given formula to calculate the sums:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;

sub submatrix_sum{
  my ($m) = @_;
  my @ret;
  foreach my $i(0..$#$m-1){
    push @ret,[];
    foreach my $j(0..$#{$m->[0]}-1){
      $ret[$i][$j] = $m->[$i][$j] + $m->[$i][$j+1] +
	$m->[$i+1][$j] + $m->[$i+1][$j+1]
    }
  }
  @ret
}

print show submatrix_sum([[1,2,3,4],[5,6,7,8],[9,10,11,12]]);
print show submatrix_sum([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]);

Sunday, December 3, 2023

TWC245

Challenge Link

Task1

Subtract 1 from popularity indices and index the array to get a sorted array by popularity:

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

sub sort_language{
  @{$_[0]}[map{$_-1}@{$_[1]}];
}

print show sort_language(['perl','c','python'],[2,1,3]);
print show sort_language(['c++','haskell','java'],[1,3,2]);


Task2

We iterate over each permutation of subsets of the array and check for the given condition:

#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(permutations subsets);

sub largest_of_three{
  my $res = -1;
  foreach my $i(0..@{$_[0]}){
    foreach my $subset(subsets $_[0],$i){
      foreach my $p(permutations $subset){
        next unless @$p;
        my $n = join '',@$p;
        $res = $n if $n > $res && $n % 3 == 0;
      }
    }
  }
  $res
}

printf "%d\n",largest_of_three([8,1,9]);
printf "%d\n",largest_of_three([8,6,7,1,0]);
printf "%d\n",largest_of_three([1]);