Cartesian product in J

Viewed 683

I'm trying to reproduce APL code for the game of life function in J. A YouTube video explaining this code can be found after searching "Game of Life in APL". Currently I have a matrix R which is:

0 0 0 0 0 0 0
0 0 0 1 1 0 0
0 0 1 1 0 0 0
0 0 0 1 0 0 0
0 0 0 0 0 0 0

I wrote J code which produces the adjacency list (number of living cells in adjacent squares) which is the following:

+/ ((#:i.4),-(#:1+i.2),(1 _1),.(_1 1)) |. R

And produces:

0 0 1 2 2 1 0
0 1 3 4 3 1 0
0 1 4 5 3 0 0
0 1 3 2 1 0 0
0 0 1 1 0 0 0

My main issue with this code is that it isn't elegant, as ((#:i.4),-(#:1+i.2),(1 _1),.(_1 1)) is needed just to produce:

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

Which is really just the outer product or Cartesian product between vectors 1 0 _1 and itself. I could not find an easy way to produce this Cartesian product, so my end question is how would I produce the required vector more elegantly?

3 Answers
Related