有什么更简洁的方法来计算 J 中列表中元素出现的次数?

发布于 2024-09-25 03:35:33 字数 220 浏览 1 评论 0原文

这是我的做法(可能很幼稚):

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

换句话说,如果我说 4 count 3 4 4 3 4 7 9 结果是 3,因为 < code>4 3 在给定列表中出现 3 次。

这非常有效,但我想知道 J 是否提供了一些更简洁的方式来表达这一点。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

凉风有信 2024-10-02 03:35:33

当我这样做时,知道我只会有一个列表而不是一个矩阵,我使用:

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

或者对于列表中的多次搜索:

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

您的方法仅复制等于 x 的元素,然后对结果进行计数。对这些项进行求和以获得相等就少了一项操作。

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.

梦与时光遇 2024-10-02 03:35:33

我同意 MPelletier 提供的算法。既然你要求简洁,那么默契的措辞可能值得一看。这是一个这样的程序,分配了一个名称:

count =: +/ @: =

它也可以用作匿名动词,如本例所示:

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

同义词是 [: +/ =

正如 MPelletier 所说,当您执行以下操作时,该算法就会起作用:想要计算一个简单列表中的原子。 (需要不同方法的类似需求是对形状相似的矩阵列表中匹配的矩阵进行计数。)

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.)

温柔女人霸气范 2024-10-02 03:35:33

我们可能还应该提到 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

所以

f =: +/ @: E.

例如

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文