Skip to content

Commit 734f7a4

Browse files
authored
Add Array Left Rotation (TheAlgorithms#2869)
1 parent 0bb7db2 commit 734f7a4

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.thealgorithms.others;
2+
3+
/*
4+
* A left rotation operation on an array
5+
* shifts each of the array's elements
6+
* given integer n unit to the left.
7+
*
8+
* @author sangin-lee
9+
*/
10+
11+
public class ArrayLeftRotation {
12+
13+
/*
14+
* Returns the result of left rotation of given array arr and integer n
15+
*
16+
* @param arr : int[] given array
17+
*
18+
* @param n : int given integer
19+
*
20+
* @return : int[] result of left rotation
21+
*/
22+
public static int[] rotateLeft(int[] arr, int n) {
23+
int size = arr.length;
24+
int[] dst = new int[size];
25+
n = n % size;
26+
for(int i = 0; i < size; i++) {
27+
dst[i] = arr[n];
28+
n = (n + 1) % size;
29+
}
30+
return dst;
31+
}
32+
33+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.others;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class ArrayLeftRotationTest {
8+
9+
@Test
10+
void testForOneElement() {
11+
int[] arr = {3};
12+
int[] result = ArrayLeftRotation.rotateLeft(arr, 3);
13+
assertArrayEquals(arr, result);
14+
}
15+
16+
@Test
17+
void testForZeroStep() {
18+
int[] arr = {3, 1, 5, 8, 6};
19+
int[] result = ArrayLeftRotation.rotateLeft(arr, 0);
20+
assertArrayEquals(arr, result);
21+
}
22+
23+
@Test
24+
void testForEqualSizeStep() {
25+
int[] arr = {3, 1, 5, 8, 6};
26+
int[] result = ArrayLeftRotation.rotateLeft(arr, 5);
27+
assertArrayEquals(arr, result);
28+
}
29+
30+
@Test
31+
void testForLowerSizeStep() {
32+
int[] arr = {3, 1, 5, 8, 6};
33+
int n = 2;
34+
int[] expected = {5, 8, 6, 3, 1};
35+
int[] result = ArrayLeftRotation.rotateLeft(arr, n);
36+
assertArrayEquals(expected, result);
37+
}
38+
39+
@Test
40+
void testForHigherSizeStep() {
41+
int[] arr = {3, 1, 5, 8, 6};
42+
int n = 7;
43+
int[] expected = {5, 8, 6, 3, 1};
44+
int[] result = ArrayLeftRotation.rotateLeft(arr, n);
45+
assertArrayEquals(expected, result);
46+
}
47+
48+
}

0 commit comments

Comments
 (0)