Rafraîchissoir

By Shahed Nooshmand

The Weekly Challenge: week 78

Task #1

You are given an array @A containing distinct integers.

Write a script to find all leader elements in the array @A. Print (0) if none found.

An element is leader if it is greater than all the elements to its right side.

Here’s one way to do it:

my @A = 9, 10, 7, 5, 6, 1;
say gather for @A {
	.take if $_ after all @A[++$ .. *];
}

I took a more generic approach and used after, which works for any type, not just numbers. Also note the $ variable.

Again, no need to print (0) if none found; the last element is always a leader element. (There is indeed no leader element in an empty array, but showing (0) might just mean “there is one leader element and it’s 0”. Empty arrays exist for a reason.)

Task #2

You are given array @A containing positive numbers and @B containing one or more indices from the array @A.

Write a script to left rotate @A so that the number at the first index of @B becomes the first element in the array. Similary, left rotate @A again so that the number at the second index of @B becomes the first element in the array.

There’s a method for that.

my @A = 10, 20, 30, 40, 50;
my @B = 3, 4;
say @A.rotate($_) for @B;

rotate takes any number, not just indices of @A. If the number passed is greater than the size of the array, the rotation wraps around. Negative numbers also work in the opposite direction.