I am trying to implement the following procedure in Java. I have an array where each element is a triplet. For example:
int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };
I want to swap every triplet in the array (with the others triplets at their right hand) in order to get each of the following matrix:
b = { {1,2,1},{0,1,0},{1,0,0},{0,2,0} };
c = { {1,0,0},{1,2,1},{0,1,0},{0,2,0} };
d = { {0,2,0},{1,2,1},{1,0,0},{0,1,0} };
e = { {0,1,0},{{1,0,0},{1,2,1},{0,2,0} };
f = { {0,1,0},{0,2,0},{1,0,0},{1,2,1} };
g = { {0,1,0},{1,2,1},{0,2,0},{1,0,0} };
In general for a Matrix of k triplets there are [(k*(k-1))/2] possibles swap.
How do I solve the problem?
A doubly-nested loop should work here. Note that the output for which you are asking is actually a 3D array (array of 2D arrays):
public int[][] copy2DArray (int[][] input) {
int[][] output = new int[input.length][];
for (int r=0; r < input.length; ++r) {
output[r] = new int[input[r].length];
for (int c=0; c < input[0].length; ++c) {
output[r][c] = input[r][c];
}
}
return output;
}
public static void main(String[] args) {
int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };
int numSwaps = a.length*(a.length-1) / 2;
int[][][] result = new int[numSwaps][][];
int counter = 0;
for (int i=0; i < a.length-1; ++i) {
for (int j=i+1; j < a.length; ++j) {
result[counter] = copy2DArray(a);
int[] temp = result[counter][j];
result[counter][j] = result[counter][i];
result[counter][i] = temp;
++counter;
}
}
System.out.println(Arrays.deepToString(result));
}
This prints:
[
[[1, 2, 1], [0, 1, 0], [1, 0, 0], [0, 2, 0]],
[[1, 0, 0], [1, 2, 1], [0, 1, 0], [0, 2, 0]],
[[0, 2, 0], [1, 2, 1], [1, 0, 0], [0, 1, 0]],
[[0, 1, 0], [1, 0, 0], [1, 2, 1], [0, 2, 0]],
[[0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 2, 1]],
[[0, 1, 0], [1, 2, 1], [0, 2, 0], [1, 0, 0]]
]
For some notes, the strategy I used to is to loop over all positions swap positions, using a two level for
loop. For each possible swap, we start by cloning your input 2D a
array. Then, we swap the individual 1D arrays at whatever positions are chosen. Finally, we add that swapped array to the 3D result array. We could have also used something like a list to store the swapped 2D arrays.