Last active
April 9, 2017 11:35
-
-
Save shashwatbhatt/a0d530b12cce46a361133c72eec27e68 to your computer and use it in GitHub Desktop.
Implementing Spiral in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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