Codility lessons #3

Wojciech Trawiński
JavaScript everyday
2 min readJan 14, 2019

Cyclic rotation

Just another day with Codility lessons 😏 Today it’s time to rotate an array!

Task description

The aim of the task is to write a function which takes an array of integers as its first argument alongside rotations count as the second one. An array’s rotation means shifting right each collection’s item by one index, except for the last element which gets the first index.

The task’s detailed description can be found here.

Solution

The first thing I had to determine was the so-called efficient rotations count (shiftCount). It was possible to skip rotations resulting in obtaining an array with items at their initial positions, hence I was interested only in the division remainder, namely the efficient rotations count.

If the rotations count (K) had been equal to the array’s (A) length, it would have been pointless to perform any operations at all. Had the above-mentioned condition been fulfilled, the function would have simply returned the input collection.

Otherwise, a new rotated array was created with the aid of rotateArray function. The goal was accomplished by using the slice method which enables to retrieve a piece of the source collection by giving start/end indexes.

The first array of the last K items was created by preceding the value with ‘-’ sign. If an index is a negative integer, an array’s length is added to the number in order to get the resulting index. If the second index is not specified, an array’s length is taken by default.

The second array contained the elements that had to be shifted right. It was computed as the source collection without the trailing K items.

Finally, the rotated array was computed based on the two collections by moving elements of the second array to the end and placing the first array’s item at the beginning. The arrays were concatenated with the aid of spread operator.

Conclusions

In order to solve the task, it was necessary to make use of the slice method. It is a very powerful tool to obtain a source array’s chunk based on start/end indexes. In addition, negative values are supported as well, which is a very handy way to get n last elements or all items but for n last. The spread operator is a nifty alternative to the concat method.

--

--