Problem 42 » 履歴 » バージョン 1
Noppi, 2024/01/16 01:52
1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
---|---|---|---|
2 | # [[Problem 42]] |
||
3 | |||
4 | ## Coded Triangle Numbers |
||
5 | The $n$<sup>th</sup> term of the sequence of triangle numbers is given by, $t_n = \frac12n(n+1)$; so the first ten triangle numbers are: |
||
6 | |||
7 | $$1, 3, 6, 10, 15, 21, 28, 36, 45, 55, \dots$$ |
||
8 | |||
9 | 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 = t_{10}$. If the word value is a triangle number then we shall call the word a triangle word. |
||
10 | |||
11 | Using [words.txt](https://projecteuler.net/resources/documents/0042_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? |
||
12 | |||
13 | ## 符号化三角数 |
||
14 | 三角数のn項は t<sub>n</sub> = n(n+1)/2で与えられる. 最初の10項は |
||
15 | |||
16 | $$1, 3, 6, 10, 15, 21, 28, 36, 45, 55, \dots$$ |
||
17 | |||
18 | である. |
||
19 | |||
20 | 単語中のアルファベットを数値に変換した後に和をとる. この和を「単語の値」と呼ぶことにする. 例えば SKY は 19 + 11 + 25 = 55 = t<sub>10</sub>である. 単語の値が三角数であるとき, その単語を三角語と呼ぶ. |
||
21 | |||
22 | 16Kのテキストファイル [words.txt](https://projecteuler.net/resources/documents/0042_words.txt) 中に約2000語の英単語が記されている. 三角語はいくつあるか? |
||
23 | |||
24 | ```scheme |
||
25 | (import (scheme base) |
||
26 | (gauche base) |
||
27 | (scheme file)) |
||
28 | |||
29 | (define words (string-split |
||
30 | (call-with-output-string |
||
31 | (^[string-port] |
||
32 | (format string-port |
||
33 | "~a" |
||
34 | (call-with-input-file |
||
35 | "words.txt" |
||
36 | (^[file-port] |
||
37 | (read-line file-port)) |
||
38 | :element-type :character)))) |
||
39 | #[","] 'suffix #f 1)) |
||
40 | |||
41 | (define (words-num words) |
||
42 | (map (^s |
||
43 | (fold (^[c n] |
||
44 | (+ n |
||
45 | (- (char->integer c) |
||
46 | (char->integer #\A) |
||
47 | -1))) |
||
48 | |||
49 | 0 |
||
50 | (string->list s))) |
||
51 | words)) |
||
52 | |||
53 | (define (triangle-num num) |
||
54 | (let loop ([index 1] [lis '()]) |
||
55 | (let ([current (/ (* index |
||
56 | (+ index 1)) |
||
57 | 2)]) |
||
58 | (if (< num current) |
||
59 | (reverse lis) |
||
60 | (loop (+ index 1) (cons current lis)))))) |
||
61 | |||
62 | (define (match-triangle-num words) |
||
63 | (let* ([words-num-list (words-num words)] |
||
64 | [triangle-num-list (triangle-num |
||
65 | (apply max words-num-list))]) |
||
66 | (filter (^n |
||
67 | (find (cut = n <>) |
||
68 | triangle-num-list)) |
||
69 | words-num-list))) |
||
70 | |||
71 | (define answer-42 |
||
72 | (length (match-triangle-num words))) |
||
73 | |||
74 | (format #t "42: ~d~%" answer-42) |
||
75 | ``` |