From 91d05769a82b32841324c97c840fd024522ddbd5 Mon Sep 17 00:00:00 2001 From: alxkm Date: Sun, 25 Aug 2024 21:15:04 +0200 Subject: [PATCH] refactor: ArrayLeftRotationTest --- .../others/ArrayLeftRotation.java | 42 ++++++++++++------- .../others/ArrayLeftRotationTest.java | 7 ++++ 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java b/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java index f43841f1f184..b54cbec08f74 100644 --- a/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java +++ b/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java @@ -1,34 +1,44 @@ package com.thealgorithms.others; -/* - * A left rotation operation on an array - * shifts each of the array's elements - * given integer n unit to the left. +/** + * Provides a method to perform a left rotation on an array. + * A left rotation operation shifts each element of the array + * by a specified number of positions to the left. * * @author sangin-lee */ - public final class ArrayLeftRotation { private ArrayLeftRotation() { } - /* - * Returns the result of left rotation of given array arr and integer n - * - * @param arr : int[] given array - * - * @param n : int given integer + /** + * Performs a left rotation on the given array by the specified number of positions. * - * @return : int[] result of left rotation + * @param arr the array to be rotated + * @param n the number of positions to rotate the array to the left + * @return a new array containing the elements of the input array rotated to the left */ public static int[] rotateLeft(int[] arr, int n) { int size = arr.length; - int[] dst = new int[size]; + + // Handle cases where array is empty or rotation count is zero + if (size == 0 || n <= 0) { + return arr.clone(); + } + + // 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++) { - dst[i] = arr[n]; - n = (n + 1) % size; + rotated[i] = arr[(i + n) % size]; } - return dst; + + return rotated; } } diff --git a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java index 355f107ddb61..b31b7d825ed5 100644 --- a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java +++ b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java @@ -44,4 +44,11 @@ void testForHigherSizeStep() { int[] result = ArrayLeftRotation.rotateLeft(arr, n); assertArrayEquals(expected, result); } + + @Test + void testForEmptyArray() { + int[] arr = {}; + int[] result = ArrayLeftRotation.rotateLeft(arr, 3); + assertArrayEquals(arr, result); + } }