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

  • Context: Java 
  • Thread starter Thread starter physicsfun
  • Start date Start date
  • Tags Tags
    Arrays Java Rotating
Click For Summary
SUMMARY

The forum discussion centers on a Java code snippet intended to rotate a 2D array 90 degrees to the left. The provided code incorrectly maintains the original dimensions of the array, resulting in an output that does not reflect a proper rotation. Specifically, the line result[i][k] = source[source.length-1-i][i]; mismanages the indices, leading to an incorrect transformation of the array elements.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with 2D arrays in Java
  • Knowledge of array indexing and manipulation
  • Basic concepts of matrix rotation
NEXT STEPS
  • Learn how to implement matrix rotation algorithms in Java
  • Study the differences between 2D array dimensions before and after rotation
  • Explore Java's array manipulation techniques and best practices
  • Investigate common pitfalls in array indexing and how to avoid them
USEFUL FOR

Java developers, computer science students, and anyone interested in understanding array manipulation and matrix transformations in programming.

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?
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
1K
Replies
8
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 13 ·
Replies
13
Views
4K
  • · Replies 17 ·
Replies
17
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K