Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate non square two dimensional array twice to have all possible rotations?

You can find a lot of answers to "rotate square two dimensional array", but not "rotate non square two dimensional array", and even though some answers do work like this one:

    rotate(tab) {                                                            
        return tab[0].map(function(col, i) {                                 
            return tab.map(function(lig) {                                   
                return lig[i];                                               
            })                                                               
        });                                                                  
    }

They only work the first time you rotate. If you rotate again, you go back to the first array, which is not what I want, I want all 3 possible combinations of an array rotated by 90'.

like image 457
Olivier Pons Avatar asked Mar 03 '17 14:03

Olivier Pons


People also ask

How do you rotate an array 90 degrees?

Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.


1 Answers

You could use the length of the array for calculating the new positions.

original   left    right
-------- -------- --------
1  2  3   4  1     3  6
4  5  6   5  2     2  5
          6  3     1  4

function rotateRight(array) {
    var result = [];
    array.forEach(function (a, i, aa) {
        a.forEach(function (b, j, bb) {
            result[bb.length - j - 1] = result[bb.length - j - 1] || [];
            result[bb.length - j - 1][i] = b;
        });
    });
    return result;
}

function rotateLeft(array) {
    var result = [];
    array.forEach(function (a, i, aa) {
        a.forEach(function (b, j, bb) {
            result[j] = result[j] || [];
            result[j][aa.length - i - 1] = b;
        });
    });
    return result;
}

var array = [[1, 2, 3], [4, 5, 6]];

console.log(rotateLeft(array));
console.log(rotateRight(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 167
Nina Scholz Avatar answered Oct 22 '22 20:10

Nina Scholz