## Recursion problem on Codewars Kata - Snail Trail

Very new to coding so please bear with me. I am attempting to solve this Kata on Codewars: https://www.codewars.com/kata/snail/train/javascript

Basically given an array like

[ [1, 2, 3, 4], [12,13,14,5], [11,16,15,6], [10,9, 8, 7] ];

It would return `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]`

.

A snail trail spiraling around the outside of the matrix and inwards.

I am just solving for the case where the matrix is n x n where n is > 1 and an even number for now.

I got it working by declaring outputarray outside the function but I want that array to be declared within the function, hence the inclusion of this line: `var outputarray = outputarray || [];`

Not sure where I am going wrong.

snail = function(array) { if (array.length == 0) { return outputarray } var n = array[0].length - 1; var outputarray = outputarray || []; for (var i = 0; i <= n; i++) { outputarray.push(array[0].splice(0, 1)); } for (var i = 1; i <= n; i++) { outputarray.push(array[i].splice(n, 1)); } for (var i = n - 1; i >= 0; i--) { outputarray.push(array[n].splice(i, 1)); } for (var i = n - 1; i > 0; i--) { outputarray.push(array[i].splice(0, 1)); } array.pop(); array.shift(); snail(array); }

One option is to define another function inside `snail`

, which calls itself recursively, while also defining the `outputarray`

inside `snail`

. That way, `outputarray`

isn't exposed to the outer scope, but the recursive function can still see it.

Also note that `splice`

returns an array, so right now, your `outputarray`

gets composed of an array of arrays. Spread into `push`

instead to fix it, so that the `outputarray`

becomes an array of numbers:

const input = [ [1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7] ]; const snail = (array) => { const outputarray = []; const iter = () => { if (array.length == 0) { return } var n = array[0].length - 1; for (var i = 0; i <= n; i++) { outputarray.push(...array[0].splice(0, 1)); } for (var i = 1; i <= n; i++) { outputarray.push(...array[i].splice(n, 1)); } for (var i = n - 1; i >= 0; i--) { outputarray.push(...array[n].splice(i, 1)); } for (var i = n - 1; i > 0; i--) { outputarray.push(...array[i].splice(0, 1)); } array.pop(); array.shift(); iter(array); }; iter(array); return outputarray; } console.log(snail(input));

**Kata Retrospective: Snail,** Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle ==1==WARNING: invalid path to external symbolizer! I'm guessing this is an issue with the kata in regards to how we coded it. I felt dumb when i saw other people solving it in few lines and me using recursion :D� Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential. Snail crawls up. 15 15 9 92% of

Here's a non-recursive approach that doesn't mutate the input `array`

. It works by keeping track of the top-left coordinate `x, y`

and the size `n`

of the spiral.

snail = function(array) { const { length } = array; const result = []; let x = 0; let y = 0; let n = length; while (n > 0) { // travel right from top-left of spiral for (let i = x; i < x + n; ++i) result.push(array[y][i]); // shrink spiral and move top of spiral down n--; y++; // travel down from top-right of spiral for (let i = y; i < y + n; ++i) result.push(array[i][x + n]); // travel left from bottom-right of spiral for (let i = x + n - 1; i >= x; --i) result.push(array[y + n - 1][i]); // shrink spiral n--; // travel up from bottom-left of spiral for (let i = y + n - 1; i >= y; --i) result.push(array[i][x]); // move left of spiral right x++; } return result; } console.log(snail([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]));

**Collection: Recursion,** mastery through challenge. Train on kata in the dojo and reach your highest potential. Recursion problems, levels 8 to 5 Tail recursion with trampoline. The SQL version of this kata should contain better instructions, like that the result should contain 17 rows, with numbers from 0 to 16 as a column named "n" and another column named "fact", with the factorial value of "n", also that you are not allowed to use CREATE FUNCTION, intead should use WITH RECURSIVE cte.

You could take some borders for the left, right, upper and lower indices and loop until no more indices are available.

function snail(array) { var upper = 0, lower = array.length - 1, left = 0, right = array[0].length - 1, i = upper, j = left, result = []; while (true) { if (upper++ > lower) break; for (; j < right; j++) result.push(array[i][j]); if (right-- < left) break; for (; i < lower; i++) result.push(array[i][j]); if (lower-- < upper) break; for (; j > left; j--) result.push(array[i][j]); if (left++ > right) break; for (; i > upper; i--) result.push(array[i][j]); } result.push(array[i][j]); return result; } console.log(...snail([[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]));

**Kata Stats: Recursion: An introduction,** The definition of a recursive function is rather simple: A function that calls itself, until something causes it not to. This means that to write a� Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential. Snail. 2198 2198 459 94% of

This may not be according to the rules (or spirit?) of the kata, however, you can just glue it all together and sort.

function snail(trail) { const numeric = (a, b) => a - b const gather = (items, item) => items.push(parseInt(item, 10)) && items const inline = (route, points) => points.reduce(gather, route) && route const order = paths => paths.reduce(inline, []).sort(numeric) return order(trail) } const trail = [ [1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7] ] console.log(JSON.stringify(snail(trail)))

**Automedon / CodeWars-7-kyu-Soluitions-part-2 Template,** CodeWars 7 kyu Solutions (Please leave a star thank you) Created by https:// github.com/Automedon - Automedon/CodeWars-7-kyu-Soluitions-part-2. Snail kata in Python @ Codewars. GitHub Gist: instantly share code, notes, and snippets.

**Try this:**

const input = [ [1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7] ]; function snail(array) { var res = []; if (!array.length) return res; var next = array.shift(); if (next) res = res.concat(next); for (var i = 0; i < array.length; i++) { res.push(array[i].pop()); } next = array.pop() if (next) res = res.concat(next.reverse()); for (var i = array.length - 1; i >= 0; i--) { res.push(array[i].shift()); } return res.concat(snail(array)); } console.log(snail(input));

**javascript - Проблема рекурсии на Codewars Kata,** Проблема рекурсии на Codewars Kata - Snail Trail snail = function(array) { if ( array.length == 0) { return outputarray } var n = array[0].length - 1; var� // In this kata we want to test, if you are able to extend the functionality of standard prototypes. // Extend the Array prototype in order to support the methods square(), cube(), average(), sum(), even() and odd(). // Explanation: // square() must return a copy of the array, containing all values squared, the original array must not be changed

My solutions for https://www.codewars.com : A collection of TDD katas (simple programs) written in JavaScript, TypeScript, Python, Rust and C++ to learn and have fun! - e1r0nd/codewars

I have not yet solved this problem, just tried with reverse order and it accepted (tested many times). If somebody can review my code and tell me why my trail of used cells not resetted to savepoint with recursion collapse, and acts like it global. Well, anyway, more complex tests are needed. UPD: Added "True" true solution.

Shouldn't for 6 * 6 . Solution should be the below array [ending in 3,2 , rather than ending in 3,1]. I am trying to understand why 1 is not allowed in 3,2 is it becuase the row below it (2,2) is 1 .If this is the reason then why 1 is allowed in 3,3 when row below it i.e 2,3 has a one.Please help me understand .

##### Comments

- Take a look at this: jsfiddle.net/e3skjtrn/1
- Another Q & A gives some good approaches. (I like my solutions involving a slice-and-transpose recursion.) And there are many other approaches in many languages in stackoverflow.com/questions/726756
- This seems like the only answer that actually attempts to answer the OP's question :)
- I think the point was to traverse in a path of a spiral, not return a sorted list of values (e.g., switching 4 and 3 should result in [1, 2, 4, 3...etc.).
- It should be noted, though, that this solution mutates the original. To my mind, that's disqualifying. (And yes, I know that this is easy to fix.)
- @ScottSauyet mine isn't the only answer here that mutates the original, is it?
- @ScottSauyet this is for demonstration only. I would prefer a more efficient solution in practice without transposition :)
- No, just the first one I read. And I recall you answering an earlier version of this question in a non-mutating manner. And as this is mostly a puzzle, I imagine, and not likely to run out of stack space or other resources, I'd usually prefer the cleanest solution unless it proves impractically slow.
- @ScottSauyet how do you define "clean?"