我正在解决Project Euler的一些编程挑战。挑战如下:
Using 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. 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 53 = 49714.
What is the total of all the name scores in the file?
所以我用咖啡脚本写了它,但我会解释逻辑,所以它是可以理解的。
fs = require 'fs'
total = 0
fs.readFile './names.txt', (err,names) ->
names = names.toString().split(',')
names = names.sort()
for num in [0..(names.length-1)]
asc = 0
for i in [1..names[num].length]
asc += names[num].charCodeAt(i-1) - 64
total += num * asc
console.log total
所以基本上,我正在读取文件。我将名称拆分成一个数组并对它们进行排序。我正在遍历每个名字。当我循环时,我正在通过每个角色获取它的charCode(作为它的所有大写)。然后我将它减去64以获得它在字母表中的位置。最后,我将总变量添加到num of the loop * sum of positions of all letters
。
我得到的答案是870873746
,但它不正确,其他答案的数字略高。
谁能明白为什么?
答案 0 :(得分:2)
total += num * asc
我认为这是出错的地方。 num
的循环从0开始(这就是计算机如何存储东西)。但是对于排名,开始应该是从1而不是0.因此,为了填充total
计数,代码应该是:
total += (num+1) * asc