Stuart2041 - 1 year ago 76
Java Question

# Friend array recursive

I'm trying to do the friend array recursively, one array is friend of another one if

`arr1[i][j] = arr2[j][i]`
so I tried to do it recursively but I only change the first row, the other keeps the same, I have to do it only with 1 array I mean I can't create two the changes I guess have to be on the same array, I did this :

``````int friendArray[][] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};

friendArrayRecursive(friendArray, 0,0);

private static void friendArrayRecursive(int[][] arr, int row, int col){
if(row < arr.length){
if (col < arr[row].length) {
arr[row][col] = arr[col][row];
friendArrayRecursive(arr, row, col + 1);
} else {
friendArrayRecursive(arr, row + 1, 0);

}
}
}
``````

But the output instead of be :

``````1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
``````

is

``````1 5 9 13
5 6 10 14
9 10 11 15
13 14 15 16
``````

How can I save the other value to change the 2 for the 5 etc...?

As nhouser9 said, you need to swap the values by using a temporary variable. Then of course, if you go through all cells, the swap will happens twice and thus it will be cancelled. So you need to go through half of the array only using the comparison (col < row).

``````private static void friendArrayRecursive(int[][] arr, int row, int col){
if(row < arr.length){
if (col < row) {
int temp = arr[row][col];
arr[row][col] = arr[col][row];
arr[col][row] = temp;
friendArrayRecursive(arr, row, col + 1);
} else {
friendArrayRecursive(arr, row + 1, 0);
}
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download