如何在javascript中旋转数组中的矩阵

编程入门 行业动态 更新时间:2024-10-11 11:19:14
本文介绍了如何在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中旋转数组中的矩阵

本文发布于:2023-11-30 07:00:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649101.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   组中   如何在   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!