John
John

Reputation: 335

Rotation of indices of a 2d array by 90 degrees

I know how to rotate an entire 2d array by 90 degrees around the center(My 2d array lengths are always odd numbers), but I need to find an algorithm that rotates specific indices of a 2d array of known length. For example I know that the 2d array is a 17 by 17 grid and I want the method to rotate the indices [4][5] around the center by 90 degrees and return the new indices as two separate ints(y,x); Please point me in the right direction or if your feeling charitable I would very much appreciate some bits of code - preferably in java. Thanks!

Upvotes: 3

Views: 4430

Answers (3)

Alnitak
Alnitak

Reputation: 339786

Assuming cartesian coordinates (i.e. x points right, and y points up) and that your coordinates are in the form array[y][x] the center [cx, cy] of your 17x17 grid is [8, 8].

Calculate the offset [dx, dy] of your point [px, py] being [4, 5] from there, i.e. [-4, -3]

For a clockwise rotation, the new location will be [cx - dy, cy + dx]

If your array uses the Y axis pointing "downwards" then you will need to reverse some of the signs in the formulae.


For a non-geometric solution, consider that the element [0][16] needs to get mapped to [16][16], and [0][0] mapped to [0][16]. i.e. the first row maps to the last column, the second row maps to the second last column, etc.

If n is one less than the size of the grid (i.e. 16) that just means that point [y][x] will map to [x][n - y]

In theory, the geometric solution should provide the same answer - here's the equivalence:

n = 17 - 1;

c = n / 2;

dx = x - c;
dy = y - c;

nx = c - dy = c - (y - c) = 2 * c - y = n - y
ny = c + dx = c + (x - c) = x

Upvotes: 4

John
John

Reputation: 16007

The point in Cartesian space x,y rotated 90 degrees counterclockwise maps to -y,x.

An array with N columns and M rows would map to an array of M columns and N rows. The new "x" index will be non-positive, and will be made zero-based by adding M:

a[x][y] maps to a[M-y][x]

Upvotes: 1

High Performance Mark
High Performance Mark

Reputation: 78316

If you have a square array with N elements in each row/column a 90deg turn anti-/counter-clockwise sends (x,y) to (N+1-y,x) doesn't it ?

That is, if like me, you think that the top-left element in a square array is (1,1) and row numbers increase down and column numbers to the right. I guess someone who counts from 0 will have to adjust the formula somewhat.

Upvotes: 1

Related Questions