How to rotate a matrix in an array in javascript

后端 未结 4 1879
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    I don't really need to deal with indices, since I can copy the values from one place to the other, this simplifies the answer a bit:

    var grid = [
      [0,0], [0,1], [0,2], [0,3], [0,4],
      [1,0], [1,1], [1,2], [1,3], [1,4],
      [2,0], [2,1], [2,2], [2,3], [2,4],
      [3,0], [3,1], [3,2], [3,3], [3,4],
      [4,0], [4,1], [4,2], [4,3], [4,4]
    ]; 
    
    var side = Math.sqrt(grid.length);
    
    var rotate = function(d,i){
       return [Math.abs(i % side - side+1), Math.floor(i/side)]
    }
    grid = grid.map(rotate);
    

    You can see a jsfiddle here: http://jsfiddle.net/KmtPg/

提交回复
热议问题