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)
C++ anyone? Quick translation from python, posted for completeness
I am sharing this code which I designed for a different purpose; it is about finding the Column number "X", and the row number "Y" of array element @ spiral index "index". This function takes the width "w" and height "h" of the matrix, and the required "index". Of course, this function can be used to produce the same required output. I think it is the fastest possible method (as it jumps over cells instead of scanning them).
This is my very very bad solution, made from bare minimum knowledge of Java. Here I have to place units on a field in a spiral. Units cannot be placed on top of other units or on mountains or in the ocean.
To be clear. This is not a good solution. This is a very bad solution added for the fun of other people to laugh at how bad it can be done
Cudos to anyone who can actually read this
Bonus question: What is the running time of this "algorithm"? :P
I recently had a similar challenge where I had to create a 2D array and use a spiral matrix algorithm to sort and print the results. This C# code will work with a N,N 2D array. It is verbose for clarity and can likely be re-factored to fit your needs.
This is in C.
I happened to choose bad variable names. In the names T == top, L == left, B == bottom, R == right. So, tli is top left i and brj is bottom right j.
//PHP implementation