I’ve been doing the Weekly
Challenges. The
latest
involved various list analyses. (Note that this ends today.)
Task 1: Min Gap
You are given an array of integers, @ints
, increasing order.
Write a script to return the element before which you find the
smallest gap.
So we look at each pair, and store the lowest. There are functional
approaches to this but I tend to stick to the straightforward one, and
the code looks basically the same across all the languages I'm using.
Crystal:
def mingap(a)
The initial "smallest difference" is the last value minus the first.
mg = a[-1] - a[0]
mv = 0
Look at each pair.
a.each_cons(2) do |p|
Work out the difference.
delta = p[1] - p[0]
If it's smaller than previously seen, store the second value.
if delta < mg
mg = delta
mv = p[1]
end
end
mv
end
Task 2: Min Diff
You are given an array of integers, @ints
.
Write a script to find the minimum difference between any two elements.
Obviously one could do this with a combination generator, but I don't
usually bother when it's just two loops.
Raku:
sub mindiff(@a) {
This time I don't have an initialising "smallest difference" value, so
I use $n
as a flag to indicate that we haven't yet had a value.
my $md = 0;
my $n = False;
As before, loop and calculate differences.
for 0 .. @a.end - 1 -> $i {
for $i + 1 .. @a.end -> $j {
my $diff = abs(@a[$i] - @a[$j]);
If I haven't seen a value yet, or this value is lower than the
previous best, store it.
if (!$n || $diff < $md) {
$md = $diff;
$n = True;
}
}
}
$md;
}
Full code on
github.