Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
Becomes:
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?
This is my implementation, in C, O(1) memory complexity, in place rotation, 90 degrees clockwise:
For i:= 0 to X do For j := 0 to X do graphic[j][i] := graphic2[X-i][j]
X is the size of the array the graphic is in.
Simple C++ method, tho there would be a big memory overhead in a big array.
Implementation of dimple's +90 pseudocode (e.g. transpose then reverse each row) in JavaScript:
You can do this in 3 easy steps:
1)Suppose we have a matrix
2)Take the transpose of the matrix
3)Interchange rows to get rotated matrix
Java source code for this:
Output:
Whilst rotating the data in place might be necessary (perhaps to update the physically stored representation), it becomes simpler and possibly more performant to add a layer of indirection onto the array access, perhaps an interface:
If your
Matrix
already implements this interface, then it can be rotated via a decorator class like this:Rotating +90/-90/180 degrees, flipping horizontally/vertically and scaling can all be achieved in this fashion as well.
Performance would need to be measured in your specific scenario. However the O(n^2) operation has now been replaced with an O(1) call. It's a virtual method call which is slower than direct array access, so it depends upon how frequently the rotated array is used after rotation. If it's used once, then this approach would definitely win. If it's rotated then used in a long-running system for days, then in-place rotation might perform better. It also depends whether you can accept the up-front cost.
As with all performance issues, measure, measure, measure!