This week’s first challenge is as follows:
Write a script to find all leader elements in the input array @A containing distinct integers. Print (0) if none is found. An element is a leader if it is greater than all elements to its right side.
So far as I can determine the only way that none would be found is if the input array is empty. But without understanding if that is the case I’ll just explicitly code the empty result case.
I’ve been learning raku for a few weeks now. I think I’m developing a feel for the idioms and one of my favorites has to be gather/take.
sub get-leaders(@a where .all > 0) {
my @leaders = gather for ^@a -> $i {
take @a[$i] if @a[$i + 1..*].grep( {@a[$i] < $_} ).elems == 0;
}
if @leaders == Empty { return (0).List }
return @leaders;
}
So we take each element in turn @a[$i], then compare it to the remainder of the array @a[i + 1..*] by grep. If there are none (.elems == 0) then the current element is a leader and we record that fact by take into the leader array.
As I mentioned earlier I try to satisfy the requirement to record (0) for cases with no leader, despite the fact that I don’t think that is possible if the input array is not empty.