HOME SUMMARY

Problem 22

1. Problem

Names Scores

Using name.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. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth \(3+15+12+9+14=53\), is the 938th name in the list. So, COLIN would obtain a score of \(938 \cdot 53 = 49714\).

What is the total of all the name scores in the file?

名字分数

在文本文件 names.txt 中有五千多个英文名。首先将这些英文名按照字母序排序,然后计算出每个英文名的字母价值,乘以它在按字母序排序后的位置,得到的就是这个英文名的得分。

例如,按照字母序排序后,位于第 938 位的名字是 COLIN,它的字母价值是 3+15+12+9+14=53。因此,COLIN 这个英文名的得分是 938 * 53 = 49714。

上述文本文件中,所有英文名的得分之和是多少?

2. Solution

首先从文件中获取名字列表:

(defun eu22-get-names ()
  (with-current-buffer
      (url-retrieve-synchronously
       "https://projecteuler.net/resources/documents/0022_names.txt")
    (search-forward-regexp "^\"")
    (backward-char)
    (insert "(")
    (goto-char (point-max))
    (insert ")")
    (goto-char (point-min))
    (search-forward-regexp "^(")
    (replace-string "," " ")
    (goto-char (point-min))
    (search-forward-regexp "^(")
    (backward-char)
    (prog1 (read (current-buffer))
      (kill-buffer))))

(setq data (eu22-get-names))

然后排序,然后求加权和:

(cl-reduce
 '+
 (seq-map-indexed
  (lambda (e i)
    (* (1+ i) (cl-reduce '+ (mapcar (lambda (x) (- x 64))
                               (append e nil)))))
  (sort data 'string<)))