Java Why is My Java Code Not Rotating an Array 90 Degrees to the Left?

AI Thread Summary
The code provided for rotating an array 90 degrees to the left is not functioning correctly due to a misunderstanding of the rotation logic and array dimensions. The output array is defined with the same dimensions as the input array, which should instead be N x M after a 90-degree rotation. The key issue lies in the line of code that attempts to assign values from the source array to the result array. The expression result[i][k] = source[source.length-1-i][i] does not correctly map the indices for a left rotation. Specifically, the use of 'i' multiple times and 'k' only once indicates a flaw in how the elements are being accessed and assigned, leading to incorrect results. Clarifying the intended index mapping for a 90-degree left rotation is essential for correcting the code.
physicsfun
Messages
10
Reaction score
0
I am supposed to write code to rotate an array 90 degrees to the left... so my question is, why is this code not rotating my array 90 degrees to the left?

thanks for any help!



public static int[][] rotateLeft(int[][] source) {
int[][] result = new int[source.length][source[0].length];
for (int i = 0; i < result.length; i++) {
for (int k = 0; k < result[0].length; k++) {
result[k] = source[source.length-1-i];}}
return result;}
 
Technology news on Phys.org
It would be helpful if you would tell us what your code turns out to be doing instead of rotating the array 90 degrees to the left.

However, this said:

1. You take in an array of dimensions M x N, and put out an array of dimensions M x N. If it was rotated wouldn't it be N x M?

2. Just look at this line of code:

result[k] = source[source.length-1-i];

What does this do? Why does i appear three times and k just one?
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Back
Top