Task1
We sort the array and remove the minimum and maximum elements then take the average:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);
sub special_average{
my ($arr) = @_;
return 0 if @$arr < 2;
@$arr = sort {$a <=> $b} @$arr;
my @sub = splice @$arr,1,$#$arr-1;
(sum0 @sub) / @sub
}
printf "%d\n",special_average([8000,5000,6000,2000,3000,7000]);
printf "%d\n",special_average([100_000,80_000,110_000,90_000]);
printf "%d\n",special_average([2500,2500,2500,2500]);
printf "%d\n",special_average([2000]);
printf "%d\n",special_average([1000,2000,3000,4000,5000,6000]);
Task2
We sort the array and then check if the distance of all elements is the same:
#!/usr/bin/env perl
use strict;
use warnings;
sub arithmetic_progression{
my ($arr) = @_;
@$arr = sort {$a <=> $b} @$arr;
my $d = abs(shift(@$arr) - shift(@$arr));
for(my $i = 0; $i < $#$arr-1; ++$i){
return 0 if abs($arr->[$i] - $arr->[$i+1]) != $d
}
1
}
printf "%d\n",arithmetic_progression([1,3,5,7,9]);
printf "%d\n",arithmetic_progression([9,1,7,5,3]);
printf "%d\n",arithmetic_progression([1,2,4,8,16]);
printf "%d\n",arithmetic_progression([5,-1,3,1,-3]);
printf "%d\n",arithmetic_progression([1.5,3,0,4.5,6]);
No comments:
Post a Comment