I’ve been doing the Weekly
Challenges. The
latest
involved a date calculation and run-length encoding. (Note that this
ends today.)
Task 1: Day of the Year
You are given a date in the format YYYY-MM-DD
.
Write a script to find day number of the year that the given date represent.
I always like date problems, because there's such a variety of date
support across the languages I'm using (including "none at all" in Lua
and PostScript). In this case, some langauges support a day of year
calculation natively (usually calling it "ordinal"), but otherwise I
just construct a date based on the first of January for the given year
and subtract,
So for example this is Ruby which has a day-of-year built in:
def dayoftheyear(a)
Date.parse(a).yday
end
And this is Lua using my date-to-Julian-day converter:
function dayoftheyear(a)
local _a, _b, y, m, d = string.find(a, "([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])")
local d1 = ymd2jd(y, m, d)
local d0 = ymd2jd(y, 1, 1)
return d1 - d0 + 1
end
Of course, a modern strftime can do this directly with the %j
format
specification, or in a low enough level language you could pull
tm_yday
directly.
Task 2: Decompressed List
You are given an array of positive integers having even elements.
Write a script to to return the decompress list. To decompress, pick adjacent pair (i, j) and replace it with j, i times.
Another thing that varies across languages: how to take an array by
non-overlapping chunks, from the variously named built-ins and
libraries (here for Perl):
use List::Util qw(pairs);
sub decompressedlist($a) {
my @out;
foreach my $pair ( pairs @{$a} ) {
my ($k, $v) = @$pair;
push @out, ($v) x $k;
}
\@out;
}
to the mini state machine I built for Lua.
function decompressedlist(a)
local out = {}
local n = 0
for _, v in ipairs(a) do
if n == 0 then
n = v
else
for i = 1, n do
table.insert(out, v)
end
n = 0
end
end
return out
end
(And some languages have a way of appending multiple values to an
array at once, as in the Perl above, and others don't.)
Full code on
github.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.