开发者

Rotating array differently

hey, I need to rotate a 2d array in such way : 4X4-->

Input      Output
1 2 3 4   5 1 2 3 
5 6 7 8   1 2 6 4 
1 2 3 4   5 3 7 8
5 6 7 8   6 7 8 4

or for odd 5X5-->

Input            Output
1 2 3 4  5   6 1 2 3  4
6 7 8 9 10   1 2 7 8  5 
1 2 3 4  5   6 7 3 9 10
6 7 8 9 10   1 8 9 4  5
1 2 3 4  5 开发者_高级运维  2 3 4 5 10

can someone help me? as you can see there are two different rings and are gettin rotated .

plz help

Im out of ideas and luck.


You can divide the n x n array like this:

+-----------+
|\         /|
| \   1   / |
|  \     /  |
|   \   /   |
|    \ /    |
| 4   +   2 |
|    / \    |
|   /   \   |
|  /     \  |
| /   3   \ |
|/         \|
+-----------+

Then all pixels in region 1 move right one pixel, all pixels in region 2 move down one pixel, etc.

The regions can be defined mathematically. Assume the lower-left corner is (0,0), then the line dividing regions 1&4 from 2&3 is x = y, and the line dividing regions 1&2 from 3&4 is x = n - y. Then:

A pixel is in region 1 if x < y and x > n - y. (left of x=y, right of x=n-y)

A pixel is in region 2 if x > y and x > n - y. (right of x=y, right of x=n-y)

Similarly for regions 3 & 4.

You need to get the edge pixels right (some of those comparisons need an equal sign), and your code will depend on the odd-or-even-ness of the array size. But you should be able to go from there.


int [][] size = new int[sx][sx];
int [][] rot = new int[sx][sx];
int x=0;
for(int i=0;i<sx;i++)
{
    for(int j=0;j<sx;j++)
    {
        size[i][j]=x++;
    }
}

for(int i=0;i<sx;i++)
{
    for(int j=0;j<sx;j++)
    {
        System.out.print(size[i][j]+"\t");
    }
     System.out.println();

}

int n=sx-1; for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) {

    if(i<j && i>=n-j)
        rot[i+1][j]=size[i][j];

    else if(i>=j && i > n-j)
        rot[i][j-1]=size[i][j];

    else if(i>j && i <= n-j)

        rot[i-1][j]=size[i][j];

    else if(i<=j && i < n-j)
        rot[i][j+1]=size[i][j];

    }

}


How about going like this:

FIND OUTER EDGES (Hint: 0,0 to max_x,0; max_x,0 to max_x,max_y; max_x,max_y to 0,max_y; 0,max_y to 0,0)
Create a new array (call it buffer). (buffer[x][y])
buffer[1][0]=arr[0][0];
buffer[1][0]=arr[0][0];
buffer[1][0]=arr[0][0];
...
buffer[max_x][0]=arr[max_x - 1][0];

Make the next inner an "outer edge", start at 1,1 to max_x-1,max_y-1, and repeat.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜