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)
Python looping clockwise spiral code using Can Berk Güder answer.
Davidont's excellent solution in VB.Net
I love python's generators.
Testing with:
You get:
Haskell, take your pick:
C# version, handles non-square sizes as well.