I have two 2D arrays of integers of the same dimension that I need to compare. I am going to explain what I need with an example where Sjm1 is the "original" array and the Sjm2 array has the same values as Sjm1 but the values of each column are ordered in increasing order (i.e. "0" is the min value of Sjm1 in column 0 so Sjm2[0][0]=0
; then "70" is the next min value of Sjm1 in column 0 ⇒ Sjm2[1][0]=70
; and so on). I have a method to sort a "Sjm1" array to "Sjm2".
Now I need to build an "output" array (2D array of integers) where the values in each column represent the number of the row in Sjm1 array that coincides with the elements of the column in Sjm2. For example, Output[0][0]=5
because Sjm1[0][0]=366
is Sjm2[5][0]=366
; Output[1][0]=2
because Sjm1[1][0]=104
is Sjm2[2][0]=104
; and so on).
Thus, for the previously presented example, the needed output must be the following:
I tried to build a method in Java where I pass the two 2D arrays of integers but is not working as needed:
public static int[][] sec(int[][] Sjm1, int[][] Sorted_Sjm2) {
int k;
int[][] output = new int[Sjm1.length][Sjm1[0].length];
for (int j = 0; j < Sjm1.length; j++) {
k = 0;
for (int m = 0; m < Sjm1[0].length; m++) {
if (Sorted_Sjm2[j][m] == Sjm1[j][m]) {
output[j][m] = k;
k++;
}
}
}
return output;
}
The output is clearly not what I need:
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6]
I'll be glad if someone can help me.
I think you are not updating the value of k
correctly, if I understood what you need, once you find the value you are looking for just update the value of k
to the index you found the value in. Note that if you have repeated values it will only take the first it found.
public static int[][] sec(int[][] Sjm1, int[][] Sorted_Sjm2) {
int k;
int[][] output = new int[Sjm1.length][Sjm1[0].length];
for (int j = 0; j < Sjm1.length; j++) {
k = 0;
for (int m = 0; m < Sjm1[0].length; m++) {
if (Sorted_Sjm2[j][m] == Sjm1[j][m]) {
k = j;
output[j][m] = k;
break;
}
}
}
return output;
}