What is a shorter way to count the number of times an item appears in a list in J?

Here is the (possibly naive) way I did it:

count =: 4: '# (# ~ = & x) y' "1 0 1

In other words, if I say 4 count 3 4 4 3 4 7 9, the result 3is because it 4occurs 3 times in this list.

This works fine, but I wonder if J offers a shorter way to express it.

+3
source share
3 answers

When I do this, knowing that I will only have a list, not a matrix, I use:

count =: 4 : '+/x=y'

Or for multiple searches in the list:

count =: 4 : '+/x=y'"0 1

Your method copies only those elements that are equal to x, and then counts the result. Summing units for equality is another operation.

+5

, MPelletier. , . , :

count =: +/ @: =

, :

   4 (+/ @: =) 3 4 4 3 4 7 9
3

[: +/ =

MPelletier, , , , - . ( , , - , .)

+3

We should also mention Member Interval E. :

4 E. 3 4 4 3 4 7 9
0 1 1 0 1 0 0

+/ 4 E. 3 4 4 3 4 7 9
3

So

f =: +/ @: E.

eg,

4 f 3 4 4 3 4 7 9 
3
(1 0) f (1 0 3 2 4 1 0 3)
2
+3
source

Source: https://habr.com/ru/post/1766633/


All Articles