Project Euler with Ruby on WSL [Problem 8]

かなしみつつ

ネタばれはダメと気づいたので一応守りながら

問題

Largest product in a series

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

私訳

数列中の最大の積

以下の1000桁の数列中で、隣接する4つの数の積のうち最大のものは 5832 である 隣接する数を 13 に増やしたとき、積の最大値はいくつか?

解答方針

"series" と言っているからには、1次元(横方向)しか考えなくていいらしい。 なので、0 で分割し、部分列の中で 13 桁未満は捨て、 13 桁越えの中からスライドして積を探していくことにする

部分解

解答というか ruby ってこういう文字列処理楽だよなー!!!!! というお気持ちの表明。 この実質ワンライナーで 0 で分割、\n を除去、min 未満を除外、数値の配列に変換~とできる。 ブロック付きメソッドは素晴らしい。

def subseq(seq, min = 1) # split to subsequence. with minimal length
    seq.split('0')
        .map{|s| s.gsub("\n", '')}
        .filter{|s| s.length >= min}
        .map{|s| s.split('')
            .map{|d| d.to_i}}
end