Spiral matrix: Difference between revisions

No edit summary
Line 885:
var (x,y) = pos //start position
var (dx,dy) = dir //direction
l.foreach {e => x = x + dx; y = y + dy; a(y)(x) = e } //copy l elements to array using current direction
pos = (x,y)
dir = (-dy, dx) //turn
Line 902:
}
</lang>
 
Explanation: since I wouldn't find a J like solution by myself, there's not much point in blindly reimplementing it :)<br/>
So, I looked for other patterns to use.<br/>
If you see the sequence of numbers to spiral around as a tape to fold around, you can see this pattern on the lenght of tape segment to fold in each step:<br/>
N, N-1, N-1,..., 1, 1<br/>
Using this the solution becomes very simple,<br/>
1. make the list of lengths to fold<br/>
2. create the sequence to fold<br/>
3. for each segment call a fold function that keeps track of where it is and knows how to turn around<br/>
 
The code could be more compact, but I'm leaving it like this for clarity.
 
=={{header|Tcl}}==