Your task is to create an NxN spiral with a given size
.
For example, a spiral with size 5 should look like this:
00000
....0
000.0
0...0
00000
and with the size 10:
0000000000
.........0
00000000.0
0......0.0
0.0000.0.0
0.0..0.0.0
0.0....0.0
0.000000.0
0........0
0000000000
Return value should contain array of arrays, of 0
and 1
, for example for given size 5
result should be:
[[1,1,1,1,1],[0,0,0,0,1],[1,1,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Because of the edge-cases for tiny spirals, the size will be at least 5.
General rule-of-a-thumb is, that the snake made with '1' cannot touch to itself.
This challenge comes from Bugari on CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (6)
Javascript:
See it in action: codesandbox.io/s/hopeful-nash-wvvc...
Now I'm working on generalizing it to non square matrix
Definitely not as efficient as iterating through each index once and deciding on a 1 or a 0 arithmetically, but I wanted to try solving this one in a different way to see how it worked out. I'd probably go back and refactor this a bit, given the choice, but it seems to work well enough.
If we had a way of initializing the array values at 0, this method could actually be more efficient, as it wouldn't necessitate visiting every single index, just those touched by the spiral.
C
Sprial or spiral?
The title says sprial, the article says spiral.