Zig-zag matrix

From Rosetta Code
Revision as of 02:40, 3 August 2008 by 68.38.195.134 (talk) (New Challenge: Zig Zag)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Produce a zig-zag array. A zig-zag array is a square arrangement of the first N2 integers, where the numbers increase sequentially as you zig-zag along the anti-diagonals of the array. For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).

For example, given 5, produce this array:

 0  1  5  6 14
 2  4  7 13 15
 3  8 12 16 21
 9 11 17 20 22
10 18 19 23 24


J

There are a couple of succinct ways to produce these in J:

   ($ [: /:@; [: <@|.`</. i.)@,~ 5
 0  1  5  6 14
 2  4  7 13 15
 3  8 12 16 21
 9 11 17 20 22
10 18 19 23 24

   ($ [: /:@; [: <@(A.~_2|#)/. i.)@,~ 5
 0  1  5  6 14
 2  4  7 13 15
 3  8 12 16 21
 9 11 17 20 22
10 18 19 23 24