How to rotate a square two-dimensional matrix twice to have all possible rotations?

You can find many answers to “rotate a square two-dimensional array” but not “rotate a square two-dimensional array”, and although some answers do work as follows:

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

They work only at the first turn. If you rotate again, you return to the first array, which I don’t want, I want all 3 possible combinations of the array rotated 90 °.

+5
source share
2 answers

You can use the length of the array to calculate 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; } 
+2
source

You can use a small library that I wrote to support 2D mesh operations ( https://github.com/klattiation/gridl ). It also supports rotation.

 const arr = [ [1, 2, 3], [4, 5, 6], ]; const rotatedArray = gridl(arr).rotate(1).data(); // rotatedArray would look like this: // [ // [4, 1], // [5, 2], // [6, 3], // ] 

You can also rotate quite easily in other directions:

 gridl(data).rotate(1); // rotates 90 degrees gridl(data).rotate(2); // rotates 180 degrees gridl(data).rotate(3); // rotates 270 degrees gridl(data).rotate(-1); // rotates -90 degrees gridl(data).rotate(-2); // rotates -180 degrees gridl(data).rotate(-3); // rotates -270 degrees 
0
source

Source: https://habr.com/ru/post/1264987/


All Articles