What do you do if you’re asked to write a function that takes in an n x m two dimensional array (that can be square-shaped when n==m) and returns a one dimensional array of all the array’s elements in spiral order? Well, spiral order starts at the top left corner of a two-dimensional array, goes to the right, and proceeds in a spiral pattern all the way until every element has been visited.
First let’s create a function called spiral_traverse, passing in an array, and create two variables, one which will function as our count, and the other our return array or new array.
Secondly we’ll start a while loop with the condition that our counter has to be less than the length of our passed in 2D array. Each time our while loop refreshes, we define a new variable called inner_array. Inner array remember, is one of the array in our 2D array.
Now it’s time for our if statement.
If our outter array is divisible by 2 (or an even number) we enter a while loop inside our inner array to add to your return array. Conversely if outter array is odd, the new array pulls from the inner array in reverse. This is to keep the spiral motion. Put it all together and it looks like this: