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'.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With