Skip to content

Instantly share code, notes, and snippets.

@hassan-maavan
Created September 19, 2020 06:24
Show Gist options
  • Save hassan-maavan/2ed99dfcb7f788c7cd6aa61c0e67aecf to your computer and use it in GitHub Desktop.
Save hassan-maavan/2ed99dfcb7f788c7cd6aa61c0e67aecf 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. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5]
snail = function(array) {
if(array.length === 0) return [];
if(array.length === 1) return array[0];
let top = array[0].slice(0,-1);
let right = array.map(a => a[a.length - 1]);
let bottom = array[array.length - 1].slice(0, -1).reverse();
let left = array.slice(1, -1).map(b => b[0]).reverse();
let inner = array.slice(1, -1).map(c => c.slice(1, -1));
return [].concat(top, right, bottom, left, snail(inner));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment