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

No comments:

Post a Comment