Pairing elements on diagonals

44 views
Skip to first unread message

Marcin Żołek

unread,
Sep 2, 2024, 1:52:48 PMSep 2
to fo...@jsoftware.com
I came up with the following challenge and I don't know how to implement it in J.

Define a rank 2 verb f which operates on tables with elements from the set {0, 1, 2}. Example input:

   ]a =: 4 4 $ 1 0 1 1  2 2 1 1  1 2 0 1  2 0 2 2
1 0 1 1
2 2 1 1
1 2 0 1
2 0 2 2

Each element of the table besides the value has its default index given by i. . For the above example it is

   i. 4 4
 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

f should return list of pairs of indices (i, j) such that elements i-th and j-th are on the same diagonal and the value of i-th element is 1 and the value of j-th element is 2. The diagonals are given by 

   </. a
┌─┬───┬─────┬───────┬─────┬───┬─┐
│1│0 2│1 2 1│1 1 2 2│1 0 0│1 2│2│
└─┴───┴─────┴───────┴─────┴───┴─┘

The output for above example (the order of pairs in a list does not matter) is as follows

   f a
8 5
2 5
6 12
3 12
6 9
3 9
11 14


Thanks,
Marcin

Henry Rich

unread,
Sep 2, 2024, 2:13:28 PMSep 2
to fo...@jsoftware.com
   ]a =: 4 4 $ 1 0 1 1  2 2 1 1  1 2 0 1  2 0 2 2
1 0 1 1
2 2 1 1
1 2 0 1
2 0 2 2
   ]ax =. </. i.$a  NB. indexes of the diagonal elements
+-+---+-----+--------+-------+-----+--+
|0|1 4|2 5 8|3 6 9 12|7 10 13|11 14|15|
+-+---+-----+--------+-------+-----+--+
   ]ax12 =. 1 2 ((= {&(,a)) # ])&.>/ ax  NB. for each diagonal, the indexes holding 1 or 2
+-+-+---+----+-+--+--+
|0| |2 8|3 6 |7|11|  |
+-+-+---+----+-+--+--+
| |4|5  |9 12| |14|15|
+-+-+---+----+-+--+--+
   ; (,/)@:(,"0/)&.>/"1 |: ax12  NB. match each 1 with each 2, in each diagonal
 2  5
 8  5
 3  9
 3 12
 6  9
 6 12
11 14

Henry Rich
To unsubscribe from this group and stop receiving emails from it, send an email to forum+un...@jsoftware.com.

Marcin Żołek

unread,
Sep 3, 2024, 11:44:51 AMSep 3
to fo...@jsoftware.com
Thanks! I find your approach (get the indices of elements for each diagonal and then work with flattened array) very useful and universal. I came up with a less universal approach: find pairs of local indices for each diagonal and then map them to the correct indices. Your solution seems more universal to me, because finding pairs is independent of the fact that the task involved diagonals in your case, while in my case it is dependent. 

   a =: 4 4 $ 1 0 1 1  2 2 1 1  1 2 0 1  2 0 2 2
   ((I.@:(=&1)  <@:(,/)@:(,."0 1)  I.@:(=&2))/.   ;@:({&.>)   </.@:i.@:$)"2 a
 2  5
 8  5
 3  9
 3 12
 6  9
 6 12
11 14

Marcin
Reply all
Reply to author
Forward
0 new messages