How do you rotate a two dimensional array?

后端 未结 30 3586
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  日久生厌
    2020-11-22 03:20

    Implementation of dimple's +90 pseudocode (e.g. transpose then reverse each row) in JavaScript:

    function rotate90(a){
      // transpose from http://www.codesuck.com/2012/02/transpose-javascript-array-in-one-line.html
      a = Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
      // row reverse
      for (i in a){
        a[i] = a[i].reverse();
      }
      return a;
    }
    

提交回复
热议问题