我正在处理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

所以基本上,我在读文件我把这些名字分成一个数组并进行排序。我在每一个名字之间循环当我循环遍历时,我将遍历每个字符以获得它的字符码(作为它的所有大写字母)然后我将它减去64,得到它在字母表中的位置最后,我将num of the loop * sum of positions of all letters添加到总变量中。
我得到的答案是870873746,但它是不正确的,其他答案的数字略高。
有人知道为什么吗?

最佳答案

 total += num * asc

我想这就是出问题的地方。num的循环从0开始(这就是计算机存储东西的方式)但排名应该从第一位开始,而不是从0开始。因此,要填充total计数,代码应该是:
 total += (num+1) * asc

关于algorithm - 欧拉计划#22-逻辑不正确?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12810637/

10-12 00:57