Skip to content

Instantly share code, notes, and snippets.

@shashwatbhatt
Last active April 9, 2017 11:35
Show Gist options
  • Select an option

  • Save shashwatbhatt/a0d530b12cce46a361133c72eec27e68 to your computer and use it in GitHub Desktop.

Select an option

Save shashwatbhatt/a0d530b12cce46a361133c72eec27e68 to your computer and use it in GitHub Desktop.
Implementing Spiral in JavaScript
let inputArray =
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]];
//This function will traverse from top-left to bottom-right
function spiralTLToBR(array) {
let result = [];
// get the first row.
result = result.concat(array.shift());
// get the last element from remaining rows.
for (let i = 0; i < array.length; i++) {
result.push(array[i].pop());
}
// check if new elements exist. If yes then call the second function.
if (array.length > 0) {
result = result.concat(spiralBRToTL(array));
}
return result;
}
//This function will traverse from bottom-right to top-left
function spiralBRToTL(array) {
let result = [];
// get the last row.
result = result.concat((array.pop() || []).reverse());
// get the first element from remaining rows.
for (let i = array.length - 1; i >= 0; i--) {
result.push(array[i].shift());
}
// check if new elements exist. If yes then call the first function.
if (array.length > 0) {
result = result.concat(spiralTLToBR(array));
}
return result;
}
console.time("spiral");
console.log(spiralTLToBR(inputArray));
console.timeEnd("spiral");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment