如何在javascript中旋转数组中的矩阵 [英] How to rotate a matrix in an array in javascript

查看:203
本文介绍了如何在javascript中旋转数组中的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(披露,我主要是数学文盲)。

(disclosure, I'm mostly math illiterate).

我有一个这种格式的数组:

I have an array in this format:

var grid = [
  [0,0], [0,1], [0,2], [0,3],
  [1,0], [1,1], [1,2], [1,3],
  [2,0], [2,1], [2,2], [2,3],
  [3,0], [3,1], [3,2], [3,3]
];

我需要以90度的增量旋转它,所以就像这样:

I need to "rotate" it by 90deg increments, so it's like this:

var grid = [
  [3,0], [2,0], [1,0], [0,0], 
  [3,1], [2,1], [1,1], [0,1], 
  [3,2], [2,2], [1,2], [0,2], 
  [3,3], [2,3], [1,3], [0,3] 
];

如何在Javascript中完成此操作?

How do I accomplish this in Javascript?

推荐答案

归功于这个回答实际轮换方法。

我的方法非常简单。只需确定行长度是什么,然后遍历每个项目,将数组索引转换为x / y等效项,然后将链接答案中使用的方法应用于旋转。最后我将旋转的X / Y坐标转换回数组索引。

My method was pretty straightforward. Just determine what the row length was, and then iterate through each item, converting the array index to x/y equivalents and then apply the method used in the linked answer to rotate. Finally I converted the rotated X/Y coordinates back to an array index.

var grid = [
  [0,0], [0,1], [0,2], [0,3],
  [1,0], [1,1], [1,2], [1,3],
  [2,0], [2,1], [2,2], [2,3],
  [3,0], [3,1], [3,2], [3,3]
]; 

var newGrid = [];
var rowLength = Math.sqrt(grid.length);
newGrid.length = grid.length

for (var i = 0; i < grid.length; i++)
{
    //convert to x/y
    var x = i % rowLength;
    var y = Math.floor(i / rowLength);

    //find new x/y
    var newX = rowLength - y - 1;
    var newY = x;

    //convert back to index
    var newPosition = newY * rowLength + newX;
    newGrid[newPosition] = grid[i];
}

for (var i = 0; i < newGrid.length; i++)
{   
    console.log(newGrid[i])
}

输出:

[3, 0] [2, 0] [1, 0] [0, 0]  
[3, 1] [2, 1] [1, 1] [0, 1]  
[3, 2] [2, 2] [1, 2] [0, 2]  
[3, 3] [2, 3] [1, 3] [0, 3]  

小提琴为懒惰。并且 5x5网格小提琴用于演示算法适用于N个网格大小,只要它们是正方形。

Fiddle for the lazy. And a 5x5 grid fiddle to demonstrate that the algorithm works for N grid sizes as long as they are square.

这篇关于如何在javascript中旋转数组中的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆