Problem 42
- 投稿者 : rei
Original
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …
By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.
Using words.txt (right click and ‘Save Link/Target As…’), a 16K text file containing nearly two-thousand common English words, how many are triangle words?
和訳
三角数のn項は tn = ½n(n+1)で与えられる. 最初の10項は
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …
である.単語中のアルファベットを数値に変換した後に和をとる. この和を「単語の値」と呼ぶことにする. 例えば SKY は 19 + 11 + 25 = 55 = t10である. 単語の値が三角数であるとき, その単語を三角語と呼ぶ.
16Kのテキストファイル word.txt 中に約2000語の英単語が記されている. 三角語はいくつあるか?
当てにならないソースコード(F#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | open System open System.IO let problem42 () = (* n 項から limit 項までの三角数を取得する *) let rec Triangler n limit = if n > limit then [] else (n * (n + 1) / 2)::Triangler (n + 1) limit (* 単語の値を取得する *) let WordValue (s:string) = Seq.fold (fun acc c -> acc + (int c - int 'A' + 1)) 0 s (* 100項目までの三角数 *) let tri = Triangler 1 100 (* x が三角数であるか調べる *) let Istriangler x = List.exists (fun t -> t = x) tri (* words.txt から読み込んだ単語のリスト *) let words = (File.ReadAllText "words.txt").Split ',' |> List.ofArray |> List.map (fun s -> s.Replace ("\"",""))//" (* 三角数の数を取得する *) let answer = words |> List.map WordValue |> List.filter Istriangler |> List.length printfn "Problem 42 > %d" answer answer |

rei@sikios.com
コメントはまだありません。