I’ve been doing the Weekly
Challenges. The
latest
involved doing disconcerting things with arrays. (Note that this ends
today.)
Task 1: Special Average
You are given an array of integers.
Write a script to return the average excluding the minimum and
maximum of the given array.
All right, there are ways of getting minimum and maximum that are
computationally cheaper than sorting, but at this scale I couldn't be
bothered. Perl:
sub specialaverage($a) {
Find max and min.
my @a = sort {$::a <=> $::b} @{$a};
my $min = $a[0];
my $max = $a[-1];
Strip them out of the list.
my @b = grep {$_ != $min && $_ != $max} @a;
Special case if there are no items left.
if (scalar @b == 0) {
return 0;
}
Otherwise return the mean.
sum(@b) / (scalar @b);
}
Task 2: Arithmetic Progression
You are given an array of numbers.
Write a script to return true if the given array can be re-arranged
to form an arithmetic progression, otherwise return false.
A sequence of numbers is called an arithmetic progression if the
difference between any two consecutive elements is the same.
One of the examples uses floating points, which means equality is only
a wistful notion.
Ruby:
def arithmeticprogression(a0)
Set the error tolerance.
epsilon = 0.001
Sort the inputs.
a = a0.sort
Establish the interval.
delta = a[1] - a[0]
Check each remaining pair.
a.drop(1).each_slice(2) do |v|
If the delta in this pair isn't the interval we're expecting (or
rather it lies outside the tolerance bound), return a failure. If we
get to the end of the checks, return success.
if (v[1] - v[0] - delta).abs > epsilon
return false
end
end
true
end
Full code on
github.