diff options
| -rwxr-xr-x | challenge-248/perlboy1967/perl/ch1.pl | 45 | ||||
| -rwxr-xr-x | challenge-248/perlboy1967/perl/ch2.pl | 60 |
2 files changed, 105 insertions, 0 deletions
diff --git a/challenge-248/perlboy1967/perl/ch1.pl b/challenge-248/perlboy1967/perl/ch1.pl new file mode 100755 index 0000000000..f8936a8df4 --- /dev/null +++ b/challenge-248/perlboy1967/perl/ch1.pl @@ -0,0 +1,45 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 248 +- https://theweeklychallenge.org/blog/perl-weekly-challenge-248 + +Author: Niels 'PerlBoy' van Dijke + +Task 1: Shortest Distance +Submitted by: Mohammad S Anwar + +You are given a string and a character in the given string. + +Write a script to return an array of integers of size same as length of the given string such that: + +distance[i] is the distance from index i to the closest occurence of +the given character in the given string. + +The distance between two indices i and j is abs(i - j). + +=cut + +use v5.32; +use common::sense; +use feature qw(signatures); + +use Test2::V0; + +use List::MoreUtils qw(indexes); +use List::Util qw(min); + +sub shortestDistance($str,$ch) { + my @ch = split //, $str; + my @idx = indexes { $_ eq $ch } @ch; + + map { + my $i = $_; $ch[$_] eq $ch ? 0 : min(map { abs($i - $_) } @idx); + } 0 .. $#ch; +} + +is([shortestDistance('loveleetcode','e')],[3,2,1,0,1,0,0,1,2,2,1,0]); +is([shortestDistance('aaab','b')],[3,2,1,0]); + +done_testing; diff --git a/challenge-248/perlboy1967/perl/ch2.pl b/challenge-248/perlboy1967/perl/ch2.pl new file mode 100755 index 0000000000..3e7dfe51cd --- /dev/null +++ b/challenge-248/perlboy1967/perl/ch2.pl @@ -0,0 +1,60 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 248 +- https://theweeklychallenge.org/blog/perl-weekly-challenge-248 + +Author: Niels 'PerlBoy' van Dijke + +Task 2: Submatrix Sum +Submitted by: Jorg Sommrey + +You are given a NxM matrix A of integers. + +Write a script to construct a (N-1)x(M-1) matrix B having elements that are the +sum over the 2x2 submatrices of A, + +b[i,k] = a[i,k] + a[i,k+1] + a[i+1,k] + a[i+1,k+1] + +=cut + +use v5.32; +use common::sense; +use feature qw(signatures); + +use Test2::V0; + +sub submatrixSum($arRef) { + map { + my $r = $_; + [map { + $arRef->[$r][$_] + + $arRef->[$r+1][$_] + + $arRef->[$r][$_+1] + + $arRef->[$r+1][$_+1] + } 0 .. scalar(@{$arRef->[$r]}) - 2]; + } 0 .. scalar(@$arRef) - 2; +} + +is([submatrixSum([ + [ 1, 2, 3, 4], + [ 5, 6, 7, 8], + [ 9,10,11,12], +])],[ + [14,18,22], + [30,34,38], +]); + +is([submatrixSum([ + [1,0,0,0], + [0,1,0,0], + [0,0,1,0], + [0,0,0,1], +])],[ + [2,1,0], + [1,2,1], + [0,1,2], +]); + +done_testing; |
