I’ve been doing the Weekly
Challenges. The
latest
involved array filtering. (Note that this ends today.)
Task 1: Finishing Order
You are given two array of integers, @order and @friends.
The @order (size n) contains every integer from 1 to n exactly once.
The @friends contains ID in sorted in strictly increasing order.
Write a script to return the array containing IDs in finishing
order.
This is basically a filter: return the items in order that also
appear in friends, in the order in which they appear in order. (So
not quite a set intersection.)
Viewed this way it's quite easy, as in Crystal:
def finishingorder(order, friends)
wanted = friends.to_set
order.select{|x| wanted.includes?(x)}
end
(Some languages allow you to ask "does array X contain value Y"
directly, but this feels ugly to me.)
Task 2: Trionic Array
You are given an array of integer.
Write a script to return true if the given array is Trionic
otherwise return false.
An array is trionic if there exist indices 0 < p < q < n-1 such that
arr[0…p] is strictly increasing, arr[p…q] is strictly decreasing,
and arr[q…n-1] is strictly increasing.
Typst doesn't like early returns, and Scala can't even break out of a
loop. Which is probably fine for the preferred functional style, and I
dare say a Scala expert would say I shouldn't be writing this as an
iterative state machine in the first place but rather looking at each
sequential pair of values to see whether they're rising or falling.
But I have states: 0 for not started yet, 1 for the first increase, 2
for the decrease, 3 for the second increase.
Languages with a skip (Rust, Crystal, Raku) make this easier.
Raku:
sub trionicarray(@a) {
my $state = 0;
my $prev = @a[0];
for @a.skip(1) -> $n {
my $dir = 0;
if ($n > $prev) {
$dir = 1;
} elsif ($n < $prev) {
$dir = -1;
}
if ($dir == 0) {
return False;
}
given $state {
when 0 {
if ($dir == 1) {
$state = 1;
} else {
return False;
}
}
when 1 {
if ($dir == -1) {
$state = 2;
}
}
when 2 {
if ($dir == 1) {
$state = 3;
}
}
when 3 {
if ($dir == -1) {
return False;
}
}
default {
return False;
}
}
$prev = $n;
}
$state == 3;
}
Full code in all tagged languages is on
codeberg.