Problem 22 » 履歴 » バージョン 2
Noppi, 2024/01/04 15:27
| 1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
|---|---|---|---|
| 2 | # [[Problem 22]] |
||
| 3 | |||
| 4 | ## Names Scores |
||
| 5 | Using [names.txt](https://projecteuler.net/resources/documents/0022_names.txt) (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. |
||
| 6 | Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. |
||
| 7 | |||
| 8 | For example, when the list is sorted into alphabetical order, COLIN, which is worth $3 + 15 + 12 + 9 + 14 = 53$, is the $938$th name in the list. So, COLIN would obtain a score of $938 \times 53 = 49714$. |
||
| 9 | |||
| 10 | What is the total of all the name scores in the file? |
||
| 11 | |||
| 12 | ## 名前のスコア |
||
| 13 | 5000個以上の名前が書かれている46Kのテキストファイル [names.txt](https://projecteuler.net/resources/documents/0022_names.txt) を用いる. まずアルファベット順にソートせよ. |
||
| 14 | |||
| 15 | のち, 各名前についてアルファベットに値を割り振り, リスト中の出現順の数と掛け合わせることで, 名前のスコアを計算する. |
||
| 16 | |||
| 17 | たとえば, リストがアルファベット順にソートされているとすると, COLINはリストの938番目にある. またCOLINは 3 + 15 + 12 + 9 + 14 = 53 という値を持つ. よってCOLINは 938 × 53 = 49714 というスコアを持つ. |
||
| 18 | |||
| 19 | ファイル中の全名前のスコアの合計を求めよ. |
||
| 20 | |||
| 21 | ```scheme |
||
| 22 | 2 | Noppi | (import (scheme base) |
| 23 | (gauche base) |
||
| 24 | (scheme file) |
||
| 25 | (scheme read) |
||
| 26 | (scheme write) |
||
| 27 | (srfi 13)) |
||
| 28 | |||
| 29 | (define (read-name-txt filename) |
||
| 30 | (let ([temp-string (call-with-input-file |
||
| 31 | filename |
||
| 32 | (^[in] (if (not in) |
||
| 33 | (errorf "ファイルオープンに失敗しました~%") |
||
| 34 | (call-with-output-string |
||
| 35 | (^[out] (format out "(~a)" (read-line in)))))) |
||
| 36 | :element-type :character)]) |
||
| 37 | (call-with-input-string |
||
| 38 | (regexp-replace-all #/,/ temp-string " ") |
||
| 39 | (^s (read s))))) |
||
| 40 | |||
| 41 | (define (sort-names lis) |
||
| 42 | (map |
||
| 43 | (^[num name] (cons num name)) |
||
| 44 | (iota (length lis) 1) |
||
| 45 | (sort lis))) |
||
| 46 | |||
| 47 | (define (name-scores lis) |
||
| 48 | (map |
||
| 49 | (^[cell] |
||
| 50 | (let ([num (car cell)] [name (cdr cell)]) |
||
| 51 | (let ([temp-score (string-fold |
||
| 52 | (^[c index] |
||
| 53 | (+ index |
||
| 54 | (- (char->integer c) |
||
| 55 | (char->integer #\A) |
||
| 56 | -1))) |
||
| 57 | 0 |
||
| 58 | name)]) |
||
| 59 | (* num temp-score)))) |
||
| 60 | lis)) |
||
| 61 | |||
| 62 | (define answer-22 |
||
| 63 | (apply + (name-scores |
||
| 64 | (sort-names |
||
| 65 | (read-name-txt "names.txt"))))) |
||
| 66 | |||
| 67 | (format #t "22: ~d~%" answer-22) |
||
| 68 | 1 | Noppi | ``` |