Reputation: 378
System.out.println("Before decryption:");
System.out.println(Arrays.deepToString(output));
int top, bottom;
bottom = this.size-1;
for(top = 0; top<bottom; top++,bottom--){
char[] topMatrix = output[top];
char[] bottomMatrix = output[bottom];
System.out.println(top+" "+bottom);
System.arraycopy(topMatrix, 0, output[bottom], 0, size);
System.arraycopy(bottomMatrix, 0, output[top], 0, size);
}
System.out.println("After Decryption: ");
System.out.println(Arrays.deepToString(output));
}
Above is the code I am using to switch the first and last rows, then second and second to last rows and so on until it runs out rows to switch in a 2d array.
Here is the output:
Input: abcdefghi
Before decryption:
[[a, b, c], [d, e, f], [g, h, i]]
0 2
After Decryption:
[[a, b, c], [d, e, f], [a, b, c]]
So what seems to be happening here is that the arraycopy does copy the first row to the last row, but somehow the bottomMatrix variable seems to be updated to (abc) instead of its original (ghi).
What gives? It seems like its executing the first arraycopy then exiting the loop and coming back, instead of executing all the statements in the loop.
Upvotes: 1
Views: 82
Reputation: 1406
You are copying code to the same array, so when your top writes to bottom, it is overwriting bottom, and then the same thing is getting written to top. You copy abc over ghi and then try to copy abc to abc.
You should use different arrays for input and output to avoid this issue.
System.out.println("Before decryption:");
System.out.println(Arrays.deepToString(output));
int top, bottom;
bottom = this.size-1;
char[][] copy = new char[size][size];
for(top = 0; top<=bottom; top++,bottom--){
char[] topMatrix = output[top];
char[] bottomMatrix = output[bottom];
System.out.println(top+" "+bottom);
System.arraycopy(topMatrix, 0, copy[bottom], 0, size);
System.arraycopy(bottomMatrix, 0, copy[top], 0, size);
}
System.out.println("After Decryption: ");
System.out.println(Arrays.deepToString(copy));
Also note that I have changed to <= instead of <, because you are writing to a new array so in case of odd sized arrays it will not copy the center row if you use only <. For even sized arrays, the same condition will work because top>bottom after half is processed.
Upvotes: 1
Reputation: 23840
Arrays, like all objects in Java, are like pointers in C.
So char[] bottomMatrix = output[bottom];
does not copy the array, bottomMatrix
now just refers to the same memory address as output[bottom]
.
But if I'm not mistaken, you don't even have to copy, you can just reassign:
for(top = 0; top<bottom; top++,bottom--){
char[] intermediate = output[top];
output[top] = output[bottom];
output[bottom] = intermediate;
}
Upvotes: 1