Created
October 17, 2021 18:50
-
-
Save lior-amsalem/001d57ecab0bc10e5698c4778e70b479 to your computer and use it in GitHub Desktop.
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
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
/** | |
array = [[1,2,3], | |
[4,5,6], | |
[7,8,9]] | |
snail(array) #=> [1,2,3,6,9,8,7,4,5] | |
**/ | |
snail = function(array) { | |
let results = [], | |
botArray = []; | |
while(array.length) { | |
botArray=[]; | |
// step 1 - left to right | |
if(array.length) | |
results.push(...array.splice(0,1)[0]); | |
// step 2 - top to bottom | |
for(let b = 0; b < array.length; b++) | |
results.push(array[b].pop()); | |
// step 3 - right to left | |
if(array.length) | |
botArray = array.splice(array.length-1,1)[0] || []; | |
for(let a = 0; a < botArray.length; a++) | |
botArray.splice(a,0, botArray.pop()) | |
results.push(...botArray); | |
// step 4 - bottom to top | |
for(let b = 0; b < array.length; b++) | |
results.push(array[(array.length-1)-b].shift()); | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment