3

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: fig 1

figure 2: fig 2

figure 3: enter image description here

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Based on your answer I got: temp = chunk[i][j]; chunk[i][j]=chunk[j][i]; chunk[j][i] = temp; But it doesn't do anything different, the part is still the same. Help?
create a new array result and save the input[i][j] entry of the input array in the result[j][i] entry. don't work on the input array!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.