I’ve been doing the Weekly
Challenges. The
latest
involved array slicing and point filtering. (Note that this ends
today.)
Task 1: Range Sum
You are given a list o integers and pair of indices..
Write a script to return the sum of integers between the given
indices (inclusive).
Every language I'm using except for Lua has some kind of array slice
function (sometimes start and length, sometimes start and end), and
most of them have a sum function. Which together make this a
one-liner. Crystal:
def rangesum(a, s, e)
a[s .. e].sum
end
Scala:
def rangesum(a: List[Int], s: Int, e: Int): Int = {
a.slice(s, e + 1).sum
}
etc.
Task 2: Nearest Valid Point
You are given current location as two integers: x
and y
. You are
also given a list of points on the grid.
A point is considered valid if it shares either the same
x-coordinate or the same y-coordinate as the current location.
Write a script to return the index of the valid point that has the
smallest Manhattan distance to the current location. If multiple
valid points are tied for the smallest distance, return the one with
the lowest index. If no valid points exist, return -1
.
The Manhattan distance between two points (x1, y1)
and (x2, y2)
is calculated as: |x1 - x2| + |y1 - y2|
.
This could probably be done with a series of maps and filters
operating on the list of points, but I found it easier to do in a more
traditionally imperative style.
Raku:
sub nearestvalidpoint($x, $y, @points) {
Set default return index value, and an invalid distance.
my $ix = -1;
my $minmhd = -1;
Iterate over points.
for @points.kv -> $i, @p {
Check that either X or Y coordinate matches (validity test).
if (@p[0] == $x || @p[1] == $y) {
Calculate the Manhattan distance.
my $mhd = abs(@p[0] - $x) + abs(@p[1] - $y);
If it's the first valid point, or it's closer than any previous point,
store its index and the minimum distance found so far.
if ($minmhd == -1 || $mhd < $minmhd) {
$minmhd = $mhd;
$ix = $i;
}
}
}
Return the result.
$ix;
}
And in all the other languages it looks essentially the same.
Full code on
github.