Java: Rotate an array

Rotating moves every element along by the same number of places, wrapping round at the end.

What to build

A program that rotates an array to the right by k places.

Requirements

  • Read n, the n numbers, and k. Make a new array where each element at index i moves to index (i + k) mod n.
  • Print the rotated array with Arrays.toString.

Input

Line 1: n. Line 2: n whole numbers. Line 3: k.

Output

One line.

Constraints

1 ≤ n ≤ 1000; 0 ≤ k ≤ 10^9.

Example

Input:

5
1 2 3 4 5
2

Output:

[4, 5, 1, 2, 3]

Why it works

The remainder operator wraps indexes round the end of the array, and reducing k modulo n first means a huge k costs no more than a small one.

Examples

Example 1 · Input
5
1 2 3 4 5
2
Expected output
[4, 5, 1, 2, 3]
Example 2 · Input
3
7 8 9
0
Expected output
[7, 8, 9]

Hints

Hint 1

After rotating right by k, the element at index i moves to index (i + k) % n.

Hint 2

k can be larger than n: reduce it with k % n first.

Solution

Show one correct solution (try it yourself first)
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = in.nextInt();
        int k = in.nextInt() % n;
        int[] b = new int[n];
        for (int i = 0; i < n; i++) b[(i + k) % n] = a[i];
        System.out.println(Arrays.toString(b));
    }
}

Lesson: Arrays →