Skip to content

Instantly share code, notes, and snippets.

@lior-amsalem
Created October 17, 2021 18:37
Show Gist options
  • Save lior-amsalem/862b4e88c3a26a99a0decb252e6ae9ec to your computer and use it in GitHub Desktop.
Save lior-amsalem/862b4e88c3a26a99a0decb252e6ae9ec to your computer and use it in GitHub Desktop.
Function purpose is to create a NxN spiral with a given size
/**
output of size = 5 example:
00000
....0
000.0
0...0
00000
**/
var spiralize = function(size) {
function createGrid(size) {
let grid = [];
grid[0] = Array(size).fill(1);
for(let a=1;a<size;a++){
grid[a] = Array(size).fill(0);
}
return grid;
}
function spiral(grid,direction,counter,gap, distance) {
let shouldDeduct = !(direction%2);
let prevGrid = [...grid];
let startFrom = distance-gap;
switch(direction) {
case 0:
for(let a=startFrom;a<distance;a++) {
grid[grid.length-distance][a] = 1;
}
break;
case 1:
for(let a=startFrom;a<distance;a++) {
grid[a][distance-1] = 1;
}
break;
case 2:
for(let a=startFrom;a<distance;a++) {
grid[distance-1][a] = 1;
}
break;
case 3:
for(let a=startFrom;a<distance;a++) {
grid[a][grid.length-distance] = 1;
}
break;
}
if(direction >= 3) {
distance = distance-2;
direction = 0;
} else {
direction++;
}
counter++;
if(shouldDeduct) {
gap = gap-2;
}
if(counter < size-1){
return spiral(grid,direction,counter,gap,distance);
}
return prevGrid;
}
let grid = createGrid(size);
let result = spiral(grid,1,0,grid.length, grid.length);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment