40036/how-to-rotate-an-array-from-a-particular-index
Can anyone help me with the program to rotate an array from a particular index given as an input from a user.
Eg:
User input must contain length of array and position of rotation.
5, 3 1,2,3,4,5 Output: 4,5,1,2,3
This is the code for the above said problem.
import java.util.*; class Rotate { public static void main (String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); while (T>0) { int N = in.nextInt(); int D = in.nextInt(); int arr[] = new int[N]; for(int i=0;i<N;i++) { arr[i]=in.nextInt(); } int arr1[]= new int [N]; for (int j=0;j<N;j++) { arr1[j]=arr[(j+D)<N?(j+D):(j+D-N)]; } for(int j= 0;j<N;j++) { System.out.print(arr1[j]+" "); } System.out.println(); T--; } } }
Input:
1 (Number of Test Case) 5 3 1 2 3 4 5
Output:
4 5 1 2 3
private static void rotate(int[] arr, int order) { if (arr == null || order < 0) { throw new IllegalArgumentException("The array must be non-null and the order must be non-negative"); } int offset = arr.length - order % arr.length; if (offset > 0) { int[] copy = arr.clone(); for (int i = 0; i < arr.length; ++i) { int j = (i + offset) % arr.length; arr[i] = copy[j]; } } }
public static final String[] VALUES = new ...READ MORE
Either: Foo[] array = list.toArray(new Foo[list.size()]); or: Foo[] array = ...READ MORE
Here is a code I came up ...READ MORE
Hello @kartik, Yes, Blah.valueOf("A") will give you Blah.A. Note that the name ...READ MORE
Yes; the Java Language Specification writes: In the Java ...READ MORE
We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE
The thing you are worried about is ...READ MORE
You can use this method: String[] strs = ...READ MORE
there are some traditional ways that you ...READ MORE
Iterating using Iterator. Using Generics: Map<Integer, Integer> map = ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.