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 ()
    (search-forward-regexp "^\"")
    (insert "(")
    (goto-char (point-max))
    (insert ")")
    (goto-char (point-min))
    (search-forward-regexp "^(")
    (replace-string "," " ")
    (goto-char (point-min))
    (search-forward-regexp "^(")
    (prog1 (read (current-buffer))

(setq data (eu22-get-names))


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