如何旋转非正方形的二维数组两次以获取所有可能的旋转方式?

7

您可以找到很多“旋转二维正方形数组”的答案,但是没有“旋转非正方形二维数组”的答案,即使某些答案像这个一样是有效的:

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

它们只能在第一次旋转时起作用。如果您再次旋转,将返回到第一个数组,这不是我想要的,我想要对一个数组进行90度旋转后的所有3种可能组合。

2个回答

5
您可以使用数组的长度来计算新位置。
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; }


只是一个快速的问题:你的代码运行得非常完美...为什么不调用rotateLeft()两次? - Olivier Pons
1
@OlivierPons,你可以这样做,对的,你需要调用左边三次,但我喜欢有两个方向可选择。 - Nina Scholz
当在2D数组上使用forEach时,我期望第一个和第二个参数是元素和索引,但aabb是什么?为什么它们是这样的? - Ade

0
你可以使用我编写的小型库gridl来处理各种2D网格操作。它还支持旋转

const {createGridFromArray2D, rotate90} = gridl;

const array2D = [
    [1, 2, 3],
    [4, 5, 6],
];
const grid = createGridFromArray2D(array2D);
const rotationSteps = 1;
const rotatedGrid = rotate90(rotationSteps)(grid);

console.log(rotatedGrid.array2D);
// [
//     [4, 1],
//     [5, 2],
//     [6, 3],
// ]
<script src="https://cdn.jsdelivr.net/npm/gridl@0.11.9/_umd/index.min.js"></script>

你也可以很容易地将网格旋转到其他方向:

rotate(1);  // rotates 1 time clockwise (90 degrees)
rotate(2);  // rotates 2 times clockwise (180 degrees)
rotate(3);  // rotates 3 times clockwise (270 degrees)
rotate(-1); // rotates 1 time counterclockwise (-90 degrees)
rotate(-2); // rotates 2 times counterclockwise (-180 degrees)
rotate(-3); // rotates 3 times counterclockwise (-270 degrees)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接