Snail Shell pattern algorithm in JavaScript
If you want to know how to resolve this algorithm step by step follow me!
What is a Snail Shell Pattern
We always find that is has a typical spirally coiled shell and among other things we only talk about the spirally coiled shell that starts from bigger and finish at a small point.
Snail Shell Pattern Algorithm
A snail pattern algorithm as the image shows will follow the line until it finished, we will subtract the numbers from outside to the inside.
Problem
Subtract the numbers of the n Arrays and print all the consecutive numbers, following the snail shell pattern example
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]result: [ 1, 2, 3, 6, 9, 8, 7, 4, 5 ]Follow the numbers consecutively
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]result: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
First Step
Create a function called snailShellPattern it accepts an array
First Validation
Then add the validation if someone wants to add objects, strings or numbers is an easy validate we use the instanceof to check if the Array is really an Array and then other validate if is less or equal to 1 return the same for performance reasons.
Variables
I used these variables top, right, bottom, left, lng, inside and rcv
top for the first array right subtracting only the final numbers bottom the last array, left subtracting the first numbers lng the length of the array less one inside all the numbers unless top, bottom, left and rcv to recursive function.
Top and Right
I used for top cloning the array with the spread operator and getting the first array for right variable I used map and filter to get the last numbers
Bottom and Left
Bottom is the same as top and left is the same as right for we need the first numbers
Inside
The inside number, we need to map and get is the index is different of 0 and the length of the array then we filter to keep the array clean
Finally
If you see the top and the right array of objects have one same number we need to remove that same number with shift() method and pop() method and for the bottom and left we need to use reverse() method the great step in this is use the recursive snailShellPattern passing the inside arrays and it will return the numbers correctly and we only need to use the spread operator to insert it inside an array and return it.
Conclusion
It’s Very interesting how you can resolve an interesting algorithm like snail shell pattern, you need to divide the problem “Divide and Conquer” in small steps