I need to build a method in Java where the input is a 2D array of integers and get as a result a 2D array of integers where each element makes reference to a position of an elem
If I understood correctly :
IN :
{{124, 188, 24, 254, 339},
{0, 7, 77, 145, 159},
{206, 340, 280, 523, 433},
{310, 265, 151, 411, 398},
{24, 104, 0, 183, 198}}
OUT :
{{1, 1, 4, 1, 1}
{4, 4, 0, 4, 4}
{0, 0, 1, 0, 0}
{2, 3, 3, 3, 3}
{3, 2, 2, 2, 2}
Here's the code :
public static int[][] createArray(int[][] a) {
int[][] nA = new int[a.length][a[0].length];
int[] col = new int[a.length];
int minIndex = -1;
for (int i = 0; i < a.length; i++) {
// First get the col out
for (int j = 0; j < a[0].length; j++) {
col[j] = a[j][i];
}
// Loop through the col
for (int k = 0; k < a[0].length; k++) {
int min = Integer.MAX_VALUE;
// Loop through the remaining numbers of the col
for (int j = 0; j < col.length; j++) {
// Find the remaining lowest number
if (min > col[j]) {
min = col[j];
minIndex = j;
}
}
// Delete the number from the array
col[minIndex] = Integer.MAX_VALUE;
// Set this number in the final array
nA[k][i] = minIndex;
}
}
return nA;
}
There might be an easier way, but it works !