简体   繁体   中英

How to rotate an array counter clockwise and invert it vertically?

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: 图。1

figure 2: 图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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM