I’ve been doing the Weekly
Challenges. The
latest
involved list testing and matrix reconstruction. (Note that this is
open until 19 February 2023.)
Task 1: Monotonic Array
You are given an array of integers.
Write a script to find out if the given array is Monotonic. Print 1 if it is otherwise 0.
An array is Monotonic if it is either monotone increasing or decreasing.
This isn't my usual understanding of the term, in which all
differences should be equal – i.e. 1, 3, 5
would qualify but 1, 3, 4
would not. But here in effect we're asked to verify that the
direction is consistent.
In other words, all the differences are positive-or-zero, or
they're all negative-or-zero.
And therefore if I multiply the lowest difference by the highest, the
result will be positive or zero.
So that's what I do. The most compact code is in Raku:
sub monotonicarray(@l) {
my @d = @l.rotor(2 => -1).map({$_[1] - $_[0]});
return @d.min * @d.max >= 0;
}
but it's not so very much longer in a lanuage such as Lua that doesn't
have these convenience functions:
function monotonicarray(l)
local d = {}
for i = 1, #l - 1 do
table.insert(d, l[i + 1] - l[i])
end
return math.min(table.unpack(d)) * math.max(table.unpack(d)) >= 0
end
Task 2: Reshape Matrix
You are given a matrix (m x n) and two integers (r) and (c).
Write a script to reshape the given matrix in form (r x c) with the
original value in the given matrix. If you can’t reshape print 0.
I do this in three steps:
- flatten the input array of arrays (I've never had a use for
flattening in real life);
- check whether we have the right number of entries for the desired
output size;
- drop those numbers into an output list, one new row's worth at a
time.
JavaScript:
function reshapematrix(m, r, c) {
let mv = m.flat();
if (r * c != mv.length) {
return [[0]];
}
let out = [];
for (let i = 0; i < r; i++) {
out.push(mv.slice(i * c, (i + 1) * c));
}
return out;
}
and PostScript isn't wildly different except for using fewer variables.
/reshapematrix {
3 dict begin
/c exch def
/r exch def
/mx exch
[ exch
{
{
} forall
} forall
] def
r c mul mx length eq {
[
0 1 r 1 sub {
mx exch c mul c getinterval
} for
]
} {
[ [ 0 ] ]
} ifelse
end
} bind def
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.