What's a more concise way to count the number of times an element occurs in a list in J?

StackOverflow https://stackoverflow.com/questions/3798603

  •  05-10-2019
  •  | 
  •  

문제

Here's the (probably naive) way I've done 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 is 3, because 4 occurs 3 three times in the given list.

This works perfectly, but I wonder whether J offers some more concise way to phrase this.

도움이 되었습니까?

해결책

When I do this, knowing that I'm only ever going to have a list and 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 over only the elements that are equal to x, then counts the result. Summing the ones for equality is one less operation.

다른 팁

I agree with the algorithm provided by MPelletier. Since you're asking for concision, tacit phrasings may be worth looking at. Here's one such program, assigned to a name:

count =: +/ @: =

It can also be used as an anonymous verb, as in this example:

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

A synonym is [: +/ =

As MPelletier said, this algorithm works when what you want to count are atoms in a simple list. (A similar need that would require a different approach would be counting matrices matched in a list of similarly-shaped matrices.)

We should probably also mention Member of 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top