如何旋转非方形二维数组两次以进行所有可能的旋转?

时间:2017-03-03 14:13:08

标签: javascript arrays rotation

你可以找到很多“旋转方形二维数组”的答案,但不是“旋转非方形二维数组”,尽管有些答案可以像这样做:

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

它们仅在您第一次旋转时才起作用。如果你再次旋转,你会回到第一个数组,这不是我想要的,我希望旋转90'的所有3种可能的组合组合。

2 个答案:

答案 0 :(得分:2)

您可以使用数组的长度来计算新位置。

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; }




答案 1 :(得分:0)

您可以使用我编写的小型库来支持2D网格操作(https://github.com/klattiation/gridl)。它也支持旋转。

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],
// ]

您也可以轻松地在其他方向上旋转:

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