j

Keep numbers which appear in both columns, in J lang


Given a table with two columns:

1 2
3 4
2 1
1 2

I'm trying to understand how to produce a list of only the numbers which appear in both columns.

E.g. 1, 1, 1, 2, 2, 2 in this example.

I can see Nub Sieve is useful for finding unique items but if there is a way to use that in this case I'm not sure how.

I have considered a frequency table /:~ ({., #) /.~ , y to get all of the totals but I'm still unclear how I'd filter out rows which don't appear in the first column.


Solution

  • Here is one method. Reading right to left, it first transposes the array because it is simpler to work with rows than columns in J, then filters the items of column 2 that are in column 1, then filters the items of the ravelled array that are in that list.

       A =: 1 2, 3 4, 2 1,: 1 2
       (, ([ #~ e.) {: #~ e./)|: A
    1 2 1 2 1 2