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]]);
No comments:
Post a Comment