Raku Weekly Challenge #78, task 2

The second challenge is a little more abstract:

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. Similarly, left rotate @A again so that the number at the second index of @B becomes the first element in the array.

As usual this problem description has me reaching for gather/take right off.

When I don’t have a great use case in my head for what the function is used for, I name it and its parameters based on what it does.

sub rotate-array-by(:@array, :@indices) {
    gather for @indices {
	take @array.rotate: $_;
    }
}

The indices input array will drive our manipulation of the input array. To rotate array so that the element at the index specified by @indices is the first element is as simple as calling rotate. We take a result for each index, letting the caller display or format the results as desired.

Leave a comment