0

I have an array:

int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};

And I want to rotate the array from a specified range by k times i.e. from 5th element to last element:

output: {1, 2, 3, 4, 9, 8, 5, 6, 7}

I tried to adapt the algorithm to rotate from start to end of the array

public static int[] rotate(int[] nums, int k) {
    int[] a = new int[nums.length];
    for (int i = 4; i < nums.length; i++) {
        a[(i + k) % nums.length] = nums[i];
    }
    for (int i = 4; i < nums.length; i++) {
        nums[i] = a[i + 4];
    }
    return nums;
}

However, the output is: 1 2 3 4 0 0 5 6 7

Apart from copying the target elements from the original array into a temporary array and then running this algorithm, what am I doing wrong? Why is 0, 0 returned instead of 9, 8?

HC Tang
  • 31
  • 10

1 Answers1

0

Rotate an elements in an array between a specified range by a specified step:

  1. Split an array into three parts: before, range and after.

  2. Shift a specified range of array.

    2.1. Split this range into two parts: near and far.

    2.2. Swap them and concatenate back.

  3. Concatenate everything back.

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int[] rotated = rotateRange(arr, 4, arr.length, 3);
    System.out.println(Arrays.toString(rotated));
    // [1, 2, 3, 4, 8, 9, 5, 6, 7]
}
// rotate a specified range of an array by a specified step
static int[] rotateRange(int[] arr, int start, int end, int n) {
    return Stream.of(
            // three parts: 'before', 'range' and 'after'
            Arrays.stream(arr, 0, start),
            // get a specified range and rotate it by a specified step
            Arrays.stream(rotate(Arrays.copyOfRange(arr, start, end), n)),
            Arrays.stream(arr, end, arr.length))
            // flatten into one stream
            .flatMapToInt(Function.identity())
            // return an array
            .toArray();
}
// rotate an array by a specified step
static int[] rotate(int[] arr, int n) {
    // prevent circular rotation
    n = n % arr.length;
    return IntStream.concat(
            // concatenate the two parts: 'far' and 'near'
            Arrays.stream(arr, n, arr.length),
            Arrays.stream(arr, 0, n))
            // return an array
            .toArray();
}

See also: Rotating an int Array in Java using only one semicolon