Project Euler Problem 22

Names scores. 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?

Link to original description
Source code examples on Github

Erlang version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p22
% vim:syn=erlang

-mode(compile).

worth(W) -> lists:foldl(fun(E,A)-> A + E - hd("A") + 1 end,0,W).

main(_) ->
    {ok, Data} = file:read_file("p022_names.txt"),
    S = size(Data)-2,
    <<"\"", D:S/binary, "\"">> = Data,
    L = lists:sort(binary:split(D,<<"\",\"">>,[global])),
    io:format("Answer: ~p ~n", [sum(L,1,0)]).

sum([], _, A)    -> A;
sum([H|T], I, A) -> sum(T,I+1,A+worth(binary_to_list(H))*I).

Python version

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python

def worth(name): return sum(ord(letter) - ord('A') + 1 for letter in name)

txt = open("p022_names.txt")
fl  = txt.read()[1:][:-1].split('","')
fl.sort()

answer = sum((i+1) * worth(fl[i]) for i in xrange(0, len(fl)))

print "Answer %s " % answer