title: Spiral traversal of a matrix - recursive solution in JavaScript
body: <p>I'm trying to come up with a solution that takes in a matrix like this:</p>
  
  <pre><code>[[1,2,3,4],
   [5,6,7,8],
   [9,10,11,12],
   [13,14,15,16]]
  </code></pre>
  
  <p>and returns an array traversing the array as a spiral, so in this example:
  <code>[1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]</code></p>
  
  <p>I'm having trouble getting this recursive solution to work, in which the result array takes the first array, the final elements of the rest of the arrays, the bottom array in reverse order, and then the first elements of the middle arrays, and then reforms the array without that outer "shell" so that it can be recursively called on what's left until there's an array of one element in the center or a 2x2 matrix (my base cases, although the latter might not be necessary...)</p>
  
  <p>My solution, which doesn't work, is as follows. Any suggestions on how I can make this work?</p>
  
  <pre><code>var spiralTraversal = function(matriks){
    var result = [];
      var goAround = function(matrix) {
          var len = matrix[0].length;
          if (len === 1) {
              result.concat(matrix[0]);
              return result;
          }
          if (len === 2) {
              result.concat(matrix[0]);
              result.push(matrix[1][1], matrix[1][0]);
              return result;
          }
          if (len &gt; 2) {
              // right
              result.concat(matrix[0]);
              // down
              for (var j=1; j &lt; matrix.length - 1; j++) {
                  result.push(matrix[j][matrix.length -1]);
              }
              // left
              for (var l=matrix.length - 2; l &gt; 0; l--) {
                  result.push(matrix[matrix.length - 1][l]);
              }
              // up
              for (var k=matrix.length -2; k &gt; 0; k--) {
                  result.push(matrix[k][0]);
              }
          }
          // reset matrix for next loop
          var temp = matrix.slice();
          temp.shift();
          temp.pop();
          for (var i=0; i &lt; temp.length - 1; i++) {
              temp[i] = temp[i].slice(1,-1);
          }
          goAround(temp);
      };
      goAround(matriks);  
  };
  </code></pre>