Task1
for each element we count the elements which are smaller that it:
#!/usr/bin/env perl
use strict;
use warnings;
sub count_smaller{
my ($arr) = @_;
map{my $e = $_;scalar grep{$_ < $e}@$arr}@$arr;
}
printf "(%s)\n",join ',',count_smaller([8,1,2,2,3]);
printf "(%s)\n",join ',',count_smaller([6,5,4,8]);
printf "(%s)\n",join ',',count_smaller([2,2,2]);
Task2
We iterate all the subsets of of the list and accumulate the sum according to the given rules:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(min max);
use Algorithm::Combinatorics qw(subsets);
sub group_hero{
my $sum = 0;
my $it = subsets($_[0]);
while(my $c = $it->next){
$sum += (max(@$c) ** 2) * min(@$c) if @$c;
}
$sum
}
printf "%d\n", group_hero([2,1,4]);
No comments:
Post a Comment