I’m tackling some of the programming challenges on Project Euler. The challenge is as follows:
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?
So I’ve written it in coffee-script, but I will explain the logic so its understandable.
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
So basically, I’m reading the file in. I split the names into an array and sort them. I’m looping through each of the names. As I loop through I’m going through each character at getting the charCode of it (as its all capitals). I’m then subtracting it by 64 to get its position in the alphabet. Finally, I add to the total variable the num of the loop * sum of positions of all letters.
The answer I get is 870873746, however it’s incorrect and other answers have a slightly higher number.
Can anyone see why?
I think this is where it went wrong. The loop for
numstarts from 0 (thats how computers store things). But for ranking, the start should be from 1st and not 0. So for populating thetotalcount, the code should be :