Function takes array integers returns array rotated N positions

Function takes array integers returns array rotated N positions

Write a function that takes an array of integers and returns that array rotated by N positions.
For example, if N=2, given the input array [1, 2, 3, 4, 5, 6] the function should return [5, 6, 1, 2, 3, 4]

Solution: Please have java program below:

package com.javahonk;

public class ArrayRotatedByNPositions {

    public static void main(String[] args) {

        int input[] = { 1, 2, 3, 4, 5, 6 };
        int output[] = new int[input.length];
        
        //Input number
        int N = 2;
        
        int outPutNvalue = N;

        for (int i = 0; i < input.length; i++) {
            int value = input.length - N;
            if (N != 0) {
                output[i] = input[value];
                N--;
            } else {
                output[i] = input[i - outPutNvalue];
            }
            
        }

        for (int i = 0; i < output.length; i++) {
            int j = output[i];
            System.out.print(j+" ");
            
        }

    }

}

Output:

Function takes array integers returns array rotated N positions

Leave a Reply

Your email address will not be published. Required fields are marked *