Skip to content

Instantly share code, notes, and snippets.

@MrMizerakl
Last active October 20, 2016 00:12
Show Gist options
  • Save MrMizerakl/d87040a119d22568dca842bc4332f0e1 to your computer and use it in GitHub Desktop.
Save MrMizerakl/d87040a119d22568dca842bc4332f0e1 to your computer and use it in GitHub Desktop.
getSpiralMatrix
const getSpiralMatrix = (rows, columns) => {
let arr = [], i=0, j=0, iterI=0, iterJ=0;
for(let i=0;i<rows;i++){
arr[i] = [];
}
for(let zn=1;zn<=rows*columns;zn++){
if(i == iterI){
arr[i][j] = zn;
j++;
if(j==columns-iterJ){
i++;
j--;
}
} else
if(j==columns-iterJ-1){
arr[i][j] = zn;
i++;
if(i==rows-iterI){
j--;
i--;
}
} else
if(i==rows-iterI-1){
arr[i][j] = zn;
j--;
if(j<iterJ){
i--;
j++;
}
} else
if(j==iterJ){
arr[i][j] = zn;
i--;
if(i<(iterI+1)){
j++;
i++;
iterI++;
iterJ++;
}
}
}
return arr;
}
let matrix = getSpiralMatrix(4, 3);
console.log(matrix);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment