With this helper function:
Clear[makeSteps]; makeSteps[0] = {}; makeSteps[m_Integer?Positive] := Most@Flatten [ Table[
We can build the matrix as
constructMatrix[n_Integer?OddQ] := Module[{cycles, positions}, cycles = (n+1)/2; positions = Flatten[FoldList[Plus, cycles + {
To get the matrix you describe, use
constructMatrix[7]
The idea is to explore the pattern according to which the positions of consecutive numbers 1 follow. You can see that they form cycles. The zero cycle is trivial - it contains the number 1 in the position {0,0} (if we count the positions from the center). The next cycle is formed by taking the first number (2) at the position {1,-1} and adding the following steps one after another: {0, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 0} (as you move in the center). The second cycle is similar, but we must start with {2,-2} , repeat each of the previous steps twice and add the sixth step (up), repeating only once: {0, -1} . The third cycle is similar: start with {3,-3} , repeat all steps 3 times, except for {0,-1} , which is repeated only twice. The helper function makeSteps automates the process. In the main function, then we need to collect all the positions together, and then add {cycles, cycles} , since they were calculated from the center, which has the position {cycles,cycles} . Finally, we build SparseArray from these positions.
Leonid Shifrin
source share