A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fellow SO'ers could come up with a better solution.
I'm posting my solution as an answer to this question.
Example Output:
For a 3x3 matrix, the output should be:
(0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1)
Furthermore, the algorithm should support non-square matrices, so for example for a 5x3 matrix, the output should be:
(0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1) (2, -1) (2, 0) (2, 1) (-2, 1) (-2, 0) (-2, -1)
TDD, in Java.
SpiralTest.java:
Spiral.java:
I have an open source library, pixelscan, that is a python library that provides functions to scan pixels on a grid in a variety of spatial patterns. Spatial patterns included are circular, rings, grids, snakes, and random walks. There are also various transformations (e.g., clip, swap, rotate, translate). The original OP problem can be solved as follows
which yields the points
The libraries generators and transformations can be chained to change the points in a wide variety of orders and spatial patterns.
This is based on your own solution, but we can be smarter about finding the corners. This makes it easier to see how you might skip over the areas outside if M and N are very different.
and a generator based solution that is better than O(max(n,m)^2), It is O(nm+abs(n-m)^2) because it skips whole strips if they are not part of the solution.
This is my approach for a square spiral in c#, i made this some time ago, i just thought i could add it, since it's different from all the others, not the best, but just a different way, i am sure it can be adapted for a non-square too.
This approach i take the max number of steps in, instead of the max vector tho.
The main thing about this approach is the corners, there's some adjustments for the first step and the "progress" step needed to go out of the "corner" in the right bottom corner.
I made this one with a friend that adjusts the spiral to the canvas aspect ratio on Javascript. Best solution I got for a image evolution pixel by pixel, filling the entire image.
Hope it helps some one.
You can see it working on http://jsfiddle.net/hitbyatruck/c4Kd6/ . Just be sure to change the width and height of the canvas on the javascript vars and on the attributes on the HTML.
Here's c#, linq'ish.
The question's first example (3x3) would be:
The question's second example (5x3) would be: