How to rotate an array counter clockwise and invert it vertically?
-
16-06-2021 - |
Question
Say each pixel in this picture(fig 1) is an element in an array. How would I rotate it 90 degress counter-clockwise(fig 2) and invert it vertically(fig 3)?
figure 1:
figure 2:
figure 3:
My current codes are:
private static Color[][] invert(Color[][] chunk){ //same as rotate
Color[] temp;
for(int i=0;i<chunk.length/2;i++){ //reverse the data
temp=chunk[i];
chunk[i]=chunk[chunk.length-i-1];
chunk[chunk.length-i-1]=temp;
}
return chunk;
}
private static Color[][] rotate(Color[][] chunk){
int cx = chunk.length;
int cz = chunk[0].length;
Color[][] rotated = new Color[cz][cx];
for(int x=0;x<cx;++x){
for(int z=0;z<cz;++z){
rotated[z][x]=chunk[cz-z-1][x];
}
}
return rotated;
}
The invert does the same function as the rotate though. Any help?
Solution
seems like you are trying to transpose the array (fig3 = transpose(fig1)
).
use a double for loop and save in the entry [i][j]
the value of [j][i]
.
see LINK for more information on the matrix transpose...
so all in all, you can use transpose
to get fig3 and afterwards invert
to get fig2.
OTHER TIPS
Baz is right, the transpose will get the job done. It looks like your transpose method used only the source array? If you looped through the whole of both lengths, you would undo all the work you did in the first half. This transpose method works for me:
public static Color[] [] transpose (Color[] [] a){
int[] [] t = new Color [a [0].length] [a.length];
for (int i = 0 ; i < a.length ; i++){
for (int j = 0 ; j < a [0].length ; j++){
t [j] [i] = a [i] [j];
}
}
return t;
}