refactor: ArrayLeftRotationTest (#5389)

This commit is contained in:
Alex Klymenko 2024-08-25 22:08:10 +02:00 committed by GitHub
parent 3187b1f99c
commit a5f57fbfde
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 35 additions and 18 deletions

View File

@ -1,34 +1,44 @@
package com.thealgorithms.others; package com.thealgorithms.others;
/* /**
* A left rotation operation on an array * Provides a method to perform a left rotation on an array.
* shifts each of the array's elements * A left rotation operation shifts each element of the array
* given integer n unit to the left. * by a specified number of positions to the left.
* *
* @author sangin-lee * @author sangin-lee
*/ */
public final class ArrayLeftRotation { public final class ArrayLeftRotation {
private ArrayLeftRotation() { private ArrayLeftRotation() {
} }
/* /**
* Returns the result of left rotation of given array arr and integer n * Performs a left rotation on the given array by the specified number of positions.
* *
* @param arr : int[] given array * @param arr the array to be rotated
* * @param n the number of positions to rotate the array to the left
* @param n : int given integer * @return a new array containing the elements of the input array rotated to the left
*
* @return : int[] result of left rotation
*/ */
public static int[] rotateLeft(int[] arr, int n) { public static int[] rotateLeft(int[] arr, int n) {
int size = arr.length; int size = arr.length;
int[] dst = new int[size];
n = n % size; // Handle cases where array is empty or rotation count is zero
for (int i = 0; i < size; i++) { if (size == 0 || n <= 0) {
dst[i] = arr[n]; return arr.clone();
n = (n + 1) % size;
} }
return dst;
// Normalize the number of rotations
n = n % size;
if (n == 0) {
return arr.clone();
}
int[] rotated = new int[size];
// Perform rotation
for (int i = 0; i < size; i++) {
rotated[i] = arr[(i + n) % size];
}
return rotated;
} }
} }

View File

@ -44,4 +44,11 @@ class ArrayLeftRotationTest {
int[] result = ArrayLeftRotation.rotateLeft(arr, n); int[] result = ArrayLeftRotation.rotateLeft(arr, n);
assertArrayEquals(expected, result); assertArrayEquals(expected, result);
} }
@Test
void testForEmptyArray() {
int[] arr = {};
int[] result = ArrayLeftRotation.rotateLeft(arr, 3);
assertArrayEquals(arr, result);
}
} }