coidlity solution 100 cyclic rotation

Codility Cyclic Rotation – 100% Correct Solution

This is a Javascript implementation for the Codility Cyclic Rotation in Lesson 2 – Arrays.

The challenge is to rotate an array A a number of K times.

The solution is quite trivial, we just need to split the array in 2 at the K lenght-K index and then add the two array. There should be a test if K is larger then the length though, and it case it is, it should be reduced with the % operator.

Here is the 100% Javascript solution. See it in action here.

function solution (A,K) {
    if (K >= A.length) { K = K % A.length;}
    if (K == 0) return A;
    else {
        let B = A.slice(A.length-K, A.length);
        let C = A.slice(0, A.length-K);
        D = B.concat(C);
        return (D);

Leave a Reply