JSFiddle - React, Tailwind, and code Playground
JavaScript
function spiralify( matrix ) {
// stop case--if there is only one row, return the row
if ( matrix.length == 1 ) {
return matrix[0];
}
var firstRow = matrix[0]
, numRows = matrix.length
// we're going to rotate the remaining rows and put them
// in this new array
, nextMatrix = []
, newRow
, rowIdx
, colIdx = matrix[1].length - 1
;
// here's where we do the actual rotation
// take each column starting with the last and working backwards
for ( colIdx; colIdx >= 0; colIdx-- ) {
// an array to store the rotated row we'll make from this column
newRow = [];
// take each row starting with 1 (the second)
for ( rowIdx = 1; rowIdx < numRows; rowIdx++ ) {
// ...and add the item at colIdx to newRow
newRow.push( matrix[ rowIdx ][ colIdx ] );
}
nextMatrix.push( newRow );
}
// pass nextMatrix to spiralify and join the result to firstRow
firstRow.push.apply( firstRow, spiralify( nextMatrix ) );
return firstRow;
}
var arr = [ [ 0, 1, 2, 3 ],
[ 4, 5, 6, 7 ],
[ 8, 9, 10, 11 ]
];
console.log( "RESULT\t", spiralify( arr ) );
// Expected result: [ 0, 1, 2, 3, 7, 11, 10, 9, 8, 4, 5, 6 ]