如何旋转非方形二维数组两次以进行所有可能的旋转? [英] How to rotate non square two dimensional array twice to have all possible rotations?
本文介绍了如何旋转非方形二维数组两次以进行所有可能的旋转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你可以找到很多旋转方形二维数组的答案,但不是旋转非方形二维数组,尽管有些答案可以像这样做:
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];
})
});
}
它们仅在您第一次旋转时起作用。如果你再次旋转,你会回到第一个数组,这不是我想要的,我希望旋转90'的所有3种可能的组合组合。
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'.
推荐答案
您可以使用数组的长度来计算新的位置。
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; }
这篇关于如何旋转非方形二维数组两次以进行所有可能的旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文