2017-03-03 45 views
5

你可以找到很多答案为“旋转的方形二维数组”,而不是“旋转非正方形二维数组”,即使一些答案做这样的工作之一:如何两次旋转非正方形二维阵列以获得所有可能的旋转?

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

他们唯一的工作第一次旋转。如果再次旋转,则返回到第一个数组,这不是我想要的,我希望数组的所有3种可能的组合都旋转90°。

回答

1

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

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

+0

只是一个简单的问题:你的代码工作完美无缺......为什么不叫rotateLeft()两次? –

+0

@OlivierPons,你可以做到这一点,对于你来说,你可以三次打电话给左边,但我喜欢有两个方向可供选择。 –

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