Task1
We count the number of negative and positive numbers in the array and return the maximum:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(max);
sub max_positive_negative{
my ($neg,$pos) = 0 x 2;
map{$neg++ if $_ < 0;$pos++ if $_ > 0}@{$_[0]};
max $neg,$pos
}
printf "%d\n",max_positive_negative([-3,1,2,-1,3,-2,4]);
printf "%d\n",max_positive_negative([-1,-2,-3,1]);
printf "%d\n",max_positive_negative([1,2]);
Task2
For each (i,j) pair we check if the condition (i * j mod k == 0) holds and count them:
#!/usr/bin/env perl
use strict;
use warnings;
sub count_equal_divisible{
my ($arr,$k) = @_;
my $count = 0;
foreach my $i(0..@$arr-2){
foreach my $j($i+1..@$arr-1){
++$count if $arr->[$i] == $arr->[$j] && ($i*$j) % $k == 0
}
}
$count
}
printf "%d\n",count_equal_divisible([3,1,2,2,2,1,3],2);
printf "%d\n",count_equal_divisible([1,2,3],1);
No comments:
Post a Comment