2012-10-10 113 views
0

我正在解决Project Euler上的一些编程挑战。挑战如下:欧拉项目#22 - 错误的逻辑?

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,但它不正确,其他答案的号码稍高。

任何人都可以看到为什么?

回答

2
total += num * asc 

我认为这是它出错的地方。 num的循环从0开始(即计算机如何存储事物)。但对于排名,一开始应该是从第1和不为0。因此,对于填充total计数,代码应该是:

total += (num+1) * asc 
+0

这正是它。有这么多的意义,不能相信我错过了。谢谢! – Menztrual