Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit734f7a4

Browse files
authored
Add Array Left Rotation (TheAlgorithms#2869)
1 parent0bb7db2 commit734f7a4

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+
packagecom.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+
publicclassArrayLeftRotation {
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+
publicstaticint[]rotateLeft(int[]arr,intn) {
23+
intsize =arr.length;
24+
int[]dst =newint[size];
25+
n =n %size;
26+
for(inti =0;i <size;i++) {
27+
dst[i] =arr[n];
28+
n = (n +1) %size;
29+
}
30+
returndst;
31+
}
32+
33+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
packagecom.thealgorithms.others;
2+
3+
importorg.junit.jupiter.api.Test;
4+
5+
importstaticorg.junit.jupiter.api.Assertions.*;
6+
7+
classArrayLeftRotationTest {
8+
9+
@Test
10+
voidtestForOneElement() {
11+
int[]arr = {3};
12+
int[]result =ArrayLeftRotation.rotateLeft(arr,3);
13+
assertArrayEquals(arr,result);
14+
}
15+
16+
@Test
17+
voidtestForZeroStep() {
18+
int[]arr = {3,1,5,8,6};
19+
int[]result =ArrayLeftRotation.rotateLeft(arr,0);
20+
assertArrayEquals(arr,result);
21+
}
22+
23+
@Test
24+
voidtestForEqualSizeStep() {
25+
int[]arr = {3,1,5,8,6};
26+
int[]result =ArrayLeftRotation.rotateLeft(arr,5);
27+
assertArrayEquals(arr,result);
28+
}
29+
30+
@Test
31+
voidtestForLowerSizeStep() {
32+
int[]arr = {3,1,5,8,6};
33+
intn =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+
voidtestForHigherSizeStep() {
41+
int[]arr = {3,1,5,8,6};
42+
intn =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)

[8]ページ先頭

©2009-2025 Movatter.jp