From 62c83b39a13dc7f9ac2b1d51b835b53a1341bbb3 Mon Sep 17 00:00:00 2001 From: michaeltomasik Date: Sun, 3 Feb 2019 16:53:16 +0100 Subject: [PATCH] Snail --- snail.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 snail.js diff --git a/snail.js b/snail.js new file mode 100644 index 0000000..3003370 --- /dev/null +++ b/snail.js @@ -0,0 +1,34 @@ +// https://www.codewars.com/kata/snail + +// Description: +// 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] +// For better understanding, please follow the numbers of the next array consecutively: + +// array = [[1,2,3], +// [8,9,4], +// [7,6,5]] +// snail(array) #=> [1,2,3,4,5,6,7,8,9] + +snail = function(array) { + let arr = array; + let snailOutput = []; + + while(arr.length > 0) { + // Take a first row amnd save it + const firstRow = arr[0]; + snailOutput = snailOutput.concat(firstRow); + // Remove firstRow + arr.shift(); + // Rotate 90 degrees matrix + if(arr[0]) { + arr = arr[0].map((col, i) => + arr.map(row => row[row.length - 1 - i])); + } + } + return snailOutput; +} \ No newline at end of file