2013-07-19 39 views
2

我正在使用歐拉項目,我在problem 8上,我嘗試了一個簡單的蠻力:將每個連續的5位數字相乘,用結果列出一個清單,並找到更高的清單。默認函數將列表中的五個連續數字相乘:J,j701

這是我目前正試圖以J寫代碼:

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

    itl =: ("[email protected];"[email protected]":) 
    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 

,但它不工作,我不知道爲什麼。 謝謝大家。

+0

只是一個小提示:你的'itl'可以用一個簡單的使用基地的倒數(#替換。)'N =:10#.inv n' – Dane

回答

2

1.之所以(i.#N) takeFive N不工作的是,你基本上是試圖運行5{. ((i.#N)-1) }. N,但你必須使用x不是作爲一個名單,但作爲一個原子。 (&)列表(N

(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.另一種方法是結合takeFive,然後通過各種i.#N運行綁定的動詞:你可以通過設置動詞的適當left-right rank " 。要做到這一點,最好使用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 
+0

Infix dyad是完美的!謝謝! :d –