CyclicRotation – Codility – Solution

Category : Java | Sub Category : Java Programs from Coding Interviews | By Runner Dev Last updated: 2020-12-21 09:11:29 Viewed : 193


CyclicRotation – Codility – Solution

 Java solution to Codility CyclicRotation problem (Lesson 2 – Arrays) which scored 100%. The problem is to rotate an integer array K times to the right and calculate what the final array will look like. The main strategy is to use the mod operator to calculate final index after wrapping around end of array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.codility.lesson02.arrays;

public class CyclicRotation {
  public int[] solution(int[] A, int K) {
    int [] rotatedA = new int[A.length];
   
    for(int i=0; i<A.length; i++) {
      //rotated index needs to "wrap" around end of array
      int rotatedIndex = (+ K) % A.length;

      rotatedA[rotatedIndex] = A[i];
    }
    return rotatedA;
  }
}

TestNG test cases for this problem which all passed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package test.com.codility.lesson02.arrays;

import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class CyclicRotationTests {
  private CyclicRotation solution;
 
  @BeforeTest
  public void setUp() {
    solution = new CyclicRotation();
  }
 
  @DataProvider(name = "test1")
  public Object [][] createData1() {
    return new Object [][] {
      new Object [] { new int [] { 389,  76 },  3,  new int [] {  976,  38 } },
      new Object [] { new int [] {       0,  00 },  1,  new int [] {        0,  00 } },
      new Object [] { new int [] {    12,  34 },  4,  new int [] {     12,  34 } },
     
      //wrap around more than once
      new Object [] { new int [] {    12,  34 },  5,  new int [] {     41,  23 } },
     
      //wrap around more than once, with negative
      new Object [] { new int [] {   -12-34 }10,  new int [] {    -34-12 } },

      //wrap around > 10 times - same as rotate by 3 (99 mod 4 = 3)
      new Object [] { new int [] {   -12-34 }99,  new int [] {    2-34-1 } },
     
      //wrap around > 10 times - finish where it started
      new Object [] { new int [] {   -12-34 }100,  new int [] {   -12-34 } },
    };
  }
 
  @Test(dataProvider = "test1")
  public void verifySolution(int [] pA, int pK, int [] pExpectedRotatedA) {
    int [] actualRotatedA = solution.solution(pA, pK);
    Assert.assertEquals(pExpectedRotatedA.length, actualRotatedA.length);
    for(int i=0; i<pExpectedRotatedA.length; i++) {
      Assert.assertEquals(pExpectedRotatedA[i], actualRotatedA[i]);
    }
  }
}

Search
Related Articles

Leave a Comment: