1public static void swap(int x, int y, int[] arr) {
2 int temp = arr[x];
3 arr[x] = arr[y];
4 arr[y] = temp;
5}
1public static final <T> void swap (T[] a, int i, int j) {
2 T t = a[i];
3 a[i] = a[j];
4 a[j] = t;
5}
6
7public static final <T> void swap (List<T> l, int i, int j) {
8 Collections.<T>swap(l, i, j);
9}
10
11private void test() {
12 String [] a = {"Hello", "Goodbye"};
13 swap(a, 0, 1);
14 System.out.println("a:"+Arrays.toString(a));
15 List<String> l = new ArrayList<String>(Arrays.asList(a));
16 swap(l, 0, 1);
17 System.out.println("l:"+l);
18}
19
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}