# Initializing an array of relative coordinates of all adjacent 2D matrix cells

The program should output this:

_1 _1
_1  0
_1  1
0 _1
0  1
1 _1
1  0
1  1


Currently I have this code:

(4 ~: i.9) # (3 # i:1) ,. 9 \$ i:1


But I think it can be better.

Your solution relies excessively on magic numbers, such as 9 and 3. It also obscures the Cartesian-product aspect of the problem. Therefore, I think it could be better written as:

(< (< (< 4))) { ,/ > { ;~i:1


## Derivation

• (i:1) produces the list _1 0 1.
• { (i:1) ; (i:1) produces the Cartesian product:

┌─────┬────┬────┐
│_1 _1│_1 0│_1 1│
├─────┼────┼────┤
│0 _1 │0 0 │0 1 │
├─────┼────┼────┤
│1 _1 │1 0 │1 1 │
└─────┴────┴────┘


@earl points out that this reflexive expression can be written more succinctly as {;~i:1.

• > unboxes it into a 3 × 3 × 2 matrix, and ,/ flattens it into a 9 × 2 matrix:

_1 _1
_1  0
_1  1
0 _1
0  0
0  1
1 _1
1  0
1  1

• The only remaining task is to exclude the 0 0 row, which is element 4. The (< (< (<4))) { selector seems to do this job.

• Is there a difference between ,&< and ;? – Savenkov Alexey Jun 29 '14 at 19:31
• ; seems to work just as well as ,&< so I have incorporated your suggestion into the answer. – 200_success Jun 29 '14 at 20:26
• Another minor improvement: the repetitive (i:1);(i:1) could also be written using the reflexive form: ;~i:1. – earl Mar 29 '15 at 18:59
• isn't (<(<(<4))) the same as (<<<4)? – Rolf Rander Dec 11 '15 at 8:00
• How about using the difference -. to remove 0 0? As in, 0 0 -.~ ,/ > { ;~i:1. I believe it's much more idiomatic compared to removing an item by an index that could change if you increase the distance from 1. – miles Jun 25 '16 at 11:12