JS实现矩阵左右旋转90度
在做2048 有一个思想,进行数组反转
说一下要实现的目标,就把二维码当成一个平面,比如下面这个数组,进行左右滚动
1, 2, 3, 4
5, 6, 7, 8
9,10,11,12
13,14,15,16
让他左滚动
4,8,12,16
3,7,11,15
2,6,10,14
1,5, 9,13
让他 右滚动
13, 9,5,1
14,10,6,2
15,11,7,3
16,12,8,4
用js实现
function rotateQR(matrix, direction) {const m = matrix.length; // 原矩阵行数const n = matrix[0].length; // 原矩阵列数// 初始化新矩阵:新行数 = 原列数,新列数 = 原行数const newMatrix = Array.from({ length: n }, () => Array(m).fill(null));for (let i = 0; i < n; i++) {for (let j = 0; j < m; j++) {if (direction === 'left') {// 左转90度:new[i][j] = 原矩阵[j][n-1-i]newMatrix[i][j] = matrix[j][n - 1 - i];} else if (direction === 'right') {// 右转90度:new[i][j] = 原矩阵[m-1-j][i]newMatrix[i][j] = matrix[m - 1 - j][i];}}}return newMatrix;
}// 使用示例
const qrMatrix = [[1, 2, 3,4],[ 5, 6,7,8],[9,10,11,12],[13,14,15,16]
];console.log("原矩阵:");
qrMatrix.forEach(row => console.log(row));console.log("\n左转90度:");
const leftRotated = rotateQR(qrMatrix, 'left');
leftRotated.forEach(row => console.log(row));console.log("\n右转90度:");
const rightRotated = rotateQR(qrMatrix, 'right');
rightRotated.forEach(row => console.log(row));