Using names.txt, 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?

click for answer





 nameSums.rb https://raw.github.com/addamh/euler/master/022/nameSums.rb download
#!/usr/bin/env ruby

letter_array = ("A".."Z").map{|l| l }
letter_hash = Hash[letter_array.map.with_index{|*ki| ki}]

file = File.open("/Users/addam/dev/euler/022/names.txt", "r")
contents = file.read.split(",").map!{|k| k.gsub!(/^\"|\"?$/, '') }

total_score = 0
puts letter_hash["z"]
contents.sort.each_with_index do |v,i|
  name_score = 0
  v.each_char do |c|
    name_score += letter_hash["#{c}"]+1
  total_score += name_score * (i+1)
puts total_score
$ time ruby nameSums.rb
real	0m0.563s
user	0m0.538s
sys	0m0.022s