How to rotate a matrix in an array in javascript

后端 未结 4 1862
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 09:49

(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],
          


        
4条回答
  •  时光取名叫无心
    2020-12-01 10:13

    Credit goes to this answer for the actual rotation method.

    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])
    }
    

    The output:

    [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]  
    

    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.

提交回复
热议问题