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
,但它不正確,其他答案的號碼稍高。
任何人都可以看到爲什麼?
這正是它。有這麼多的意義,不能相信我錯過了。謝謝! – Menztrual