Skip to content

Instantly share code, notes, and snippets.

@themgoncalves
Created November 3, 2018 15:00
Show Gist options
  • Save themgoncalves/64e25ba111d4b502839bddb665ae1a9e to your computer and use it in GitHub Desktop.
Save themgoncalves/64e25ba111d4b502839bddb665ae1a9e to your computer and use it in GitHub Desktop.
Spiral Matrix - Outputs 2 dimensional matrix in spiral sequence
/*
* Spiral Matrix
* @function toSpiral
* @description Outputs 2 dimensional matrix in spiral sequence
* @example
* const matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
* @param {Array} matrix - 2 dimensional matrix
* @return {Array} given matrix in spiral order
*/
function toSpiral(matrix) {
let output = [];
// Iterates over the matrix while it has
// more than 1 item
// e.g. matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
while (matrix.length > 1) {
// To the right direction
// Removes the first item of the matrix.
// e.g. [[1, 2, 3],[4, 5, 6],[7, 8, 9]] => [1, 2, 3]
output = output.concat(matrix.shift());
// To the down direction
// Removes last item of each row
// e.g. [[4, 5, 6],[7, 8, 9]] => 6, 9
for (let i = 0; i < matrix.length; i += 1){
output.push(matrix[i].splice(-1)[0]);
}
// To the left direction
// Removes last item of each row
// e.g. [[4, 5],[7, 8]] => 8, 7
output = output.concat(matrix.splice(-1, 1)[0].reverse());
// To the up direction
// Removes first item of the first column each time.
// e.g. [[4, 5]] => 4
for(let i = matrix.length - 1; i >=0; i-= 1){
output.push(matrix[i].splice(0,1)[0]);
}
}
// If matrix still has value, then extracts it
// e.g. [[5]] => 5
if (matrix.length){
output.push(matrix.pop()[0]);
}
// returns matrix in spiral sequence
// e.g. [1, 2, 3, 6, 9, 8, 7, 4, 5]
return output;
}
// -------------------------------------------------
// Implementation example
const matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
console.log(toSpiral(matrix));
// will outputs [1, 2, 3, 6, 9, 8, 7, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment