algorithm - 欧拉计划 #22 - 逻辑不正确?

标签 algorithm coffeescript logic

我正在解决 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?

所以我用 coffee-script 写了它,但我会解释逻辑以便理解。

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 以获得它在字母表中的位置。最后,我将 循环次数 * 所有字母的位置总和 添加到 total 变量中。

我得到的答案是 870873746,但它不正确,其他答案的数字略高。

谁能看出原因?

最佳答案

 total += num * asc

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

 total += (num+1) * asc

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

相关文章:

node.js - 引用错误: t is not defined

c - 为什么这个大于函数起作用?

Javascript:冒泡排序

algorithm - VOIP如何计算RTP包延时

java - 斐波那契修改 :How to fix this algorithm?

javascript - 启动 backbone.js 历史记录时无法调用未定义的 'start'。

algorithm - 更有效地旋转 64 个 CCSprite?

javascript - 如何将主干模型插入子集合?

php - 不同的排名逻辑

php - (整数)假;在PHP中为什么会这样?