I’ve been doing the Weekly
Challenges. The
latest
involved an unusual base representation and date calculations. (Note
that this is open until 21 August 2022.)
Task 1: Quater-imaginary Base
Write a script to convert a given number (base 10) to
quater-imaginary base number and vice-versa.
As described
here: digits
alternate for real and imaginary components.
For Perl this doesn't matter much, but for most of the other languages
it does: what format do I use for the quater-imaginary representation?
I ended up using a string of characters - though a more compressed
version could take just two bits per place, since only digits 0..3
are allowed.
In Kotlin, I start with a convenience function (I might as well write
the full complex number conversion since it's not much more work than
the real-only one).
fun r2qi (n: Int): String {
return c2qi(n, 0)
}
Real and imaginary components are treated separately.
fun c2qi (r0: Int, i0: Int): String {
var l = ArrayList<ArrayList<Int>>()
for (n0 in listOf(i0, r0)) {
var n = n0
var digits = ArrayList<Int>()
A fairly usual base conversion by repeated division, but a modulus
operator can return a negative result, so we deal with that here.
while (n != 0) {
var digit = n % -4
n /= -4
if (digit < 0) {
digit += 4
n += 1
}
digits.add(digit)
}
l.add(digits)
}
Take the difference in length between the two arrays (for real and
imaginary parts), and pad with zeroes as needed. (There are probably
more efficient ways of doing this.)
val ld = l[0].size - l[1].size
if (ld < 0) {
for (x in 1..-ld-1) {
l[0].add(0,0)
}
} else if (ld > 1) {
for (x in 1..ld) {
l[1].add(0,0)
}
}
var o = ""
for (i in l[1].size-1 downTo 0) {
for (b in listOf(0,1)) {
if (l[b].size > i) {
o += l[b][i]
}
}
}
return o
}
Convenience function for the string-to-number conversion.
fun qi2r(n: String): Int {
return qi2c(n)[0]
}
fun qi2c(n: String): List<Int> {
var pow = 1
var ri = 0
var r = 0
var i = 0
This is rather simpler: for each digit, flip between real and
imaginary components, and increment the power. However, there's
apparently a bug in Kotlin, and I had to write this:
for (ch in n.reversed().toList()) {
if (ri == 0) {
r += (ch.digitToInt()) * pow
} else {
i += (ch.digitToInt()) * pow
}
rather than, as in all the other languages, simply using an array o
and
incrementing o[ri]
.
Increment loop variables.
ri += 1
pow *= 2
if (ri == 2) {
ri = 0
pow = -pow
}
}
return listOf(r,i)
}
This is one of the few times when Lua's 1-based arrays actually make
the code simpler.
JavaScript has a %
operator like all the other languages, but unlike
them it's not a true modulus; it's a remainder. (Which is the same
thing if both the numbers are positive.) Should you need one:
function mod(n, m) {
return ((n % m) + m) % m;
}
Task 2: Business Date
You are given $timestamp
(date with time) and $duration
in hours.
Write a script to find the time that occurs $duration business hours
after $timestamp. For the sake of this task, let us assume the
working hours is 9am to 6pm, Monday to Friday. Please ignore
timezone too.
That last bit is really hard in languages with good date handling,
and worryingly easy in others. Again I ignored Lua; in PostScript I
used a two-element array of (julian date) and (minutes since
midnight). In Raku, though:
sub addbizhours($start, $delta) {
One of the few languages that doesn't provide a strptime
-like date parser.
$start ~~ /(<[0..9]>+)\D(<[0..9]>+)\D(<[0..9]>+)\D(<[0..9]>+)\D(<[0..9]>+)/;
my $current = DateTime.new(year => $0,
month => $1,
day => $2,
hour => $3,
minute => $4,
second => 0);
my $seconds = 3600 * $delta;
my $bizdaylength = 3600 * 9;
If the current time isn't in business hours, advance to the next start
of business hours.
unless (isbiz($current)) {
$current = nextbizstart($current);
}
Find the end of the current business day.
my $ed = nextbizend($current);
Get the number of seconds between then and current.
my $remain = ($ed - $current).Int;
If the remaining span won't fit in this day:
if ($remain < $seconds) {
Knock the rest of day off the remaining span.
$seconds -= $remain;
Advance to the start of the next day.
$current = nextbizstart($ed);
And while the remaining span is more than a day length,
while ($seconds > $bizdaylength) {
Move to the start of the next business day and knock that off the span.
$current = nextbizstart($current);
$seconds -= $bizdaylength;
}
}
Finally, add any remaining seconds.
$current = $current.later(seconds => $seconds);
And return the string format (most languages offer something based on
strftime
).
return $current.yyyy-mm-dd ~ " " ~ substr($current.hh-mm-ss,0,5);
}
Are we in a business-day?
sub isbiz($tm) {
Not if it's Saturday or Sunday.
if ($tm.day-of-week > 5) {
return False;
}
Not if it's before 9am or after 6pm.
if ($tm.hour < 9 || $tm.hour >= 18) {
return False;
}
Otherwise yes.
return True;
}
Given a current time, when does the next business day start?
sub nextbizstart($tm0) {
my $tm = $tm0.clone;
While it's a weekend, advance to 9am on the next day.
while ($tm.day-of-week > 5) {
$tm = $tm.later(days => 1).
clone(hour => 9, minute => 0, second => 0);
}
If it's before 9, advance to 9,
if ($tm.hour < 9) {
$tm = $tm.clone(hour => 9, minute => 0, second => 0);
} else {
Otherwise, add a day and then jump to 9am, repeatedly if needed until
we're not at a weekend.
while (True) {
$tm = $tm.later(days => 1)
.clone(hour => 9, minute => 0, second => 0);
if ($tm.day-of-week <= 5) {
last;
}
}
}
return $tm;
}
nextbizend
works the same way with fractionally different logic.
Perl's DateTime
is pretty good (rather better than the Raku built-in
clearly inspired by it), but I think Rust's chrono
crate was my
favourite of the date libraries; alas, the date support in Ruby (using
the Time
class) is shockingly bad, especially given my generally
positive experience of the rest of the language. You can't even set
the hours part of a time entity without parsing it out into compnents
and then reassembling:
def sethour(tm,hour)
ar = tm.to_a
ar[2] = hour
return Time.utc(*ar)
end
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.