見習村21 - Snail
21 - Snail
Don’t say so much, just coding…
Instruction
Snail Sort
Given an n x n
array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
1 |
|
For better understanding, please follow the numbers of the next array consecutively:
1 |
|
NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]]
.
Ruby
Init
1 |
|
Sample Testing
1 |
|
Javascript
Init
1 |
|
Sample Testing
1 |
|
Thinking
想法(1): 需要花時間找一下規律,每次將陣列取第一個的時候,後面剩餘的陣列必須還有些動作來轉換
想法(2): 轉換直至陣列為空為止,可以透過遞迴或者是 while 迴圈來寫
圖片來源:Unsplash Dagny Reese
Hint & Reference
- Ruby
- JavaScript
Solution
Ruby
1 |
|
Javascript
1 |
|