合并此 J 代码
我正在学习 J,并从一些基本的东西开始;将 3 和 5 的倍数相加到 100 以下。我用这段代码得到了它:
(+/((((i.100)|~ 3) = 0) # (i.100)),((((i.100)|~ 5) = 0) # (i.100)))-(((i.100|~15)=0) # (i.100))
但似乎应该有一个更简单的方法。有什么办法可以让这段代码更简洁吗?谢谢。
I'm learning J and starting with something basic; adding the multiples of 3 and 5 below 100. I got it with this code:
(+/((((i.100)|~ 3) = 0) # (i.100)),((((i.100)|~ 5) = 0) # (i.100)))-(((i.100|~15)=0) # (i.100))
but it seems like there should be an easier way. Is there any way to make this code cleaner? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请注意,您当前的代码给出了长度错误,但我建议对您的问题进行编辑以使其正常工作。现在我还将包含下面的工作代码。
通过简单地改变运算顺序(J 从右到左评估“句子”),可以更简单地编写相同的算法(无论如何都可以减少括号)。
您可以使用
~.
(Nub) 从列表中删除任何重复项,而不是从原始总和中减去 15 的倍数总和来避免重复计算同时是 3 和 5 倍数的数字。 3 的倍数和 5 的倍数,然后再求和。有关此问题的更 Jish 方法,请参阅此 stackoverflow 问题的答案< /a>.
Note that your current code gives a length error but I have suggested an edit to your question to make it work. For now I'll also include the working code below.
The same algorithm can be written more simply (less parentheses anyway) by simply altering the order of operations (J evaluates "sentences" from right to left).
Rather than subtracting the sum of the multiples of 15 from the original sum to avoid double counting number that are multiples of both 3 and 5, you could use
~.
(Nub) to remove any duplicates from your list of multiples of 3 and multiples of 5 before summing them.For a more Jish approach to this problem see the answer to this stackoverflow question.