0

我正在解决 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,但它不正确,其他答案的数字略高。

谁能明白为什么?

4

1 回答 1

2
 total += num * asc

我认为这是出错的地方。for 的循环num从 0 开始(这就是计算机存储东西的方式)。但是对于排名,开始应该从 1 开始,而不是 0。所以对于填充total计数,代码应该是:

 total += (num+1) * asc
于 2012-10-10T01:32:20.757 回答