2
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ Is there a difference between ,&< and ;? \$\endgroup\$ Jun 29 '14 at 19:31
  • \$\begingroup\$ ; seems to work just as well as ,&< so I have incorporated your suggestion into the answer. \$\endgroup\$ Jun 29 '14 at 20:26
  • 1
    \$\begingroup\$ Another minor improvement: the repetitive (i:1);(i:1) could also be written using the reflexive form: ;~i:1. \$\endgroup\$
    – earl
    Mar 29 '15 at 18:59
  • \$\begingroup\$ isn't (<(<(<4))) the same as (<<<4)? \$\endgroup\$ Dec 11 '15 at 8:00
  • \$\begingroup\$ 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. \$\endgroup\$
    – miles
    Jun 25 '16 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.