【问题标题】:Tacit function to multiply five consecutive number in a list: J, j701将列表中的五个连续数字相乘的默认函数:J,j701
【发布时间】:2015-01-23 00:50:55
【问题描述】:

我正在从事 Project Euler,我在 problem 8,我正在尝试一个简单的蛮力:将数字的每个连续 5 位相乘,用结果列出一个列表,然后找到更高的。

这是我目前尝试用 J 编写的代码:

   n =: 731671765313x
   NB. 'n' will be the complete 1000-digits number

   itl =: (".@;"0@":)
   NB. 'itl' transform an integer in a list of his digit

   N =: itl n
   NB. just for short writing

   takeFive =: 5 {. ] }.~ 1 -~ [
   NB. this is a dyad, I get this code thanks to '13 : '5{.(x-1)}.y'
   NB. that take a starting index and it's applied to a list

如何将 takeFive 用于 N 的所有索引? 我试过了:

  (i.#N) takeFive N
|length error: takeFive
|   (i.#N)    takeFive N 

但它不起作用,我不知道为什么。 谢谢大家。

【问题讨论】:

  • 请注意:您的 itl 可以简单地使用 Base (#.) N =: 10 #.inv n987654325@的倒数替换

标签: loops j tacit-programming


【解决方案1】:

1.(i.#N) takeFive N 不起作用的原因是您实际上是在尝试运行5{. ((i.#N)-1) }. N,但您必须将x 用作一个原子而不是列表。您可以通过设置动词的适当left-right rank " 来做到这一点:

 (i.#N) (takeFive"0 _) N
7 3 1 6 7
7 3 1 6 7
3 1 6 7 1
1 6 7 1 7
6 7 1 7 6
7 1 7 6 5
1 7 6 5 3
7 6 5 3 1
6 5 3 1 3
5 3 1 3 0
3 1 3 0 0
1 3 0 0 0

2. 另一种方法是将列表 (N) 绑定 (&) 到 takeFive,然后通过每个 i.#N 运行绑定动词。为此,最好使用 takeFive 的反向版本:takeFive~:

((N&(takeFive~))"0) i.#N
7 3 1 6 7
7 3 1 6 7
3 1 6 7 1
1 6 7 1 7
6 7 1 7 6
7 1 7 6 5
1 7 6 5 3
7 6 5 3 1
6 5 3 1 3
5 3 1 3 0
3 1 3 0 0
1 3 0 0 0

(N&(takeFive~)) each i.#N

3. 不过,我认为infix dyad \ 可能会更好地为您服务:

5 >\N
7 3 1 6 7
3 1 6 7 1
1 6 7 1 7
6 7 1 7 6
7 1 7 6 5
1 7 6 5 3
7 6 5 3 1
6 5 3 1 3

【讨论】:

  • 中缀 dyad 是完美的!谢谢! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多