Skip to content

Instantly share code, notes, and snippets.

@hdvianna
Created April 2, 2019 19:50
Show Gist options
  • Save hdvianna/796038644eaceda0897308f8af62fdc9 to your computer and use it in GitHub Desktop.
Save hdvianna/796038644eaceda0897308f8af62fdc9 to your computer and use it in GitHub Desktop.
JS Spiral Matrix Iterator
function border(matrix, row, col, len) {
var items=[];
var endCol = col - 1;
var endRow = row;
//top
for(;col < len; col++) {
items.push(matrix[row][col]);
}
//right
col--;
row++;
for(;row < len; row++) {
items.push(matrix[row][col]);
}
//bottom
col--;
row--;
for(;col > endCol; col--) {
items.push(matrix[row][col]);
}
//left
col++;
row--;
for(;row > endRow; row--) {
items.push(matrix[row][col]);
}
return items;
}
function spiral(matrix) {
var items = [];
var i=0;
while(items.length < Math.pow(matrix.length, 2)) {
items = items.concat(border(matrix, i, i, matrix.length-i));
i++;
}
return items;
}
/**
* 0 1 2 3
* 4 5 6 7
* 8 9 10 11
* 12 13 14 15
*
* 0,1,2,3,7,11,15,14,13,12,8,4,5,6,10,9
*/
var matrix4x4 = [[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]
console.log(border(matrix4x4, 0, 0, matrix4x4.length));
console.log(spiral(matrix4x4));
/**
* 0 1 2
* 3 4 5
* 6 7 8
*
* 0,1,2,5,8,7,6,3,4
*/
var matrix3x3 = [[0,1,2],[3,4,5],[6,7,8]]
console.log(border(matrix3x3, 0, 0, matrix3x3.length));
console.log(spiral(matrix3x3));
/**
* 0 1
* 2 3
*
* 0,1,3,2
*/
var matrix2x2 = [[0,1],[2,3]]
console.log(border(matrix2x2, 0, 0, matrix2x2.length));
console.log(spiral(matrix2x2));
/**
* 0
*
* 0
*/
var matrix1x1 = [[0]]
console.log(border(matrix1x1, 0, 0, matrix1x1.length));
console.log(spiral(matrix1x1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment