-1

Suppose I have rectangular 4x8 grid represented as an array of values in javascript:

var grid = [
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,
            0, 0, 0, 0,    
];

How can I rotate this array -90 degrees to the left so that it then becomes an 8x4 grid?

I have tried toying with the solutions in other questions such as this one:

How to rotate a matrix in an array in javascript

But the answers only deal with square grids.

Any help would be greatly appreciated.

Community
  • 1
  • 1
Gordo
  • 779
  • 9
  • 21
  • I have tried toying with the solution in this question, but it only works with square grids. I'll add this to the question: http://stackoverflow.com/questions/15170942/how-to-rotate-a-matrix-in-an-array-in-javascript – Gordo Dec 23 '15 at 16:56
  • 1
    Shouldn't it be a 2 dimensional array? As it has been defined, this is just a single row of 32 values. – Steve Harris Dec 23 '15 at 16:57
  • It is represented as in javascript as a single array of 32 values, yes. But I need to re-position those values as though the 'visual' representation were rotated to the left. i.e the value at row 1 column 4 becomes the value at row 1 column 1. Or in otherwords the value in the top right corner becomes the value in the top left. – Gordo Dec 23 '15 at 17:01
  • @Gordo In the link you provided for the question you were investigating, you should just need to change the 'rowLength' to not use the square root of the total length. Make it a custom value and I think it should work. – Adam Evans Dec 23 '15 at 17:09
  • @Aderis I tried that and it didn't appear to work. – Gordo Dec 23 '15 at 17:12

1 Answers1

2
var rows = 8;
var cols = 4;
var rotatedGrid = [];
var row = 0;
var col = 0;
for (col = cols - 1; col >= 0; col--)
{
    for (row = 0; row < rows; row++)
    {
        rotatedGrid.push(grid[row * cols + col]);
    }
}
Steve Harris
  • 5,014
  • 1
  • 10
  • 25