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 = (i + 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 [] { 3, 8, 9, 7, 6 }, 3, new int [] { 9, 7, 6, 3, 8 } },
new Object [] { new int [] { 0, 0, 0 }, 1, new int [] { 0, 0, 0 } },
new Object [] { new int [] { 1, 2, 3, 4 }, 4, new int [] { 1, 2, 3, 4 } },
//wrap around more than once
new Object [] { new int [] { 1, 2, 3, 4 }, 5, new int [] { 4, 1, 2, 3 } },
//wrap around more than once, with negative
new Object [] { new int [] { -1, 2, -3, 4 }, 10, new int [] { -3, 4, -1, 2 } },
//wrap around > 10 times - same as rotate by 3 (99 mod 4 = 3)
new Object [] { new int [] { -1, 2, -3, 4 }, 99, new int [] { 2, -3, 4, -1 } },
//wrap around > 10 times - finish where it started
new Object [] { new int [] { -1, 2, -3, 4 }, 100, new int [] { -1, 2, -3, 4 } },
};
}
@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]);
}
}
}