Faffing round the edges Its easier than getting stuck in

28Mar/090

Euler 22 – Name scores in a list

It has been a while since I Euler'd but I have been mega depressed what with working in Sheffield and trying to retro-fit web security as an after thought to a web app that I was thrown at last minute...so at home, to cheer up, it is Euler time again.

I've been looking at Nitrogen a lot too. Anyhoo, the problem:

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?

I don't think this is a very mathy problem, just a programming one. I edited the file a little so I could use erlang's file:consult/1 which allows you to read a file as a set of erlang terms. I merely inserted "{names, [" at the start and "]}." (full stop =:= very important!) at the end of the file of names.

With erlang treating strings as lists it is very easy to calculate the score for a name. I used lists:foldl/3 on each name in turn after sorting the list of names. For once I find erlangs handling of strings very, very useful. The code is below.

%%%%%%
% Prob 22
% Each letter has the value ASCII code value - 64 so A = 65 - 64 so A = 1
%%%%%
problem22() ->
	%%Read the file
	{ok, Tup} = file:consult("names.txt"),
	%%Get the name list
	[{names, L}] = Tup,
	%%Sort it
	Names = lists:sort(L),
	calculate_values(Names, 1, 0).

%% Calulate the values for the names in the file
%% list of names, current iteration, current accumulated value
calculate_values([], _Iteration, Total) -> Total;
calculate_values([Name|Names], Iteration, Total) ->
	calculate_values(Names, Iteration+1, Total + calculate_value(Name, Iteration)).

%%Calulate the value for a single name (That is sum of letter scores (EG A=1) * this names position in the list of names (Iter))
calculate_value(Name, Iteration) ->
	NameScore =lists:foldl(fun(X, Acc) -> Acc + (X - 64) end, 0, Name),
	NameScore * Iteration.

It is cheating since I used the lists:sort/1 function of erlang. When I have more time I'll implement the sort too, since that would seem to be the point of the exercise.

   

 

March 2009
M T W T F S S
« Dec   Jun »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Archives