swap chunks of array in java

Solutions on MaxInterview for swap chunks of array in java by the best coders in the world

showing results for - "swap chunks of array in java"
Marcus
04 Feb 2018
1import java.util.Arrays;
2
3// ... //
4
5int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
6
7// Rotate is a fancy way to say split around an index, and swap the chunks
8// For the comments, assume `A=digits`
9int[] rotate(int[] A, int r) {
10  int N = A.length; // total number of elements
11  
12  // Arrays.copyOfRange(array, start, end) will return array[start:end),
13  // where start is inclusive and end exclusive
14  int[] left = Arrays.copyOfRange(A, 0, r); // [0,1,...,r-1], so r=3->[0,1,2]
15  int[] right = Arrays.copyOfRange(A, r, N); // [r,r+1,...,N-1], so r=7->[7,8,9]
16  
17  // Now, concatenate right with left and store in result
18  // - in JS this would be `result=[...right, ...left]`
19  int[] result = new int[N];
20  int R = N - r; // length of right array
21  for(int i=0; i<N; ++i) {
22    // ternary expression: same as
23    //   `if(i<R) result[i] = right[i];`
24    //   `else    result[i] = left[i-R];`
25    result[i] = i<R ? right[i] : left[i-R];
26  }
27  
28  return result;
29}
similar questions
queries leading to this page
swap chunks of array in java