Project Euler Problem 22 Solution

Question

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?

Haskell

import Data.List (sort)

parse :: String -> [String]
parse = words . map replaceComma . filter notQuote where
    replaceComma ',' = ' '
    replaceComma c = c
    notQuote = (/= '"')

alphaIndex :: Char -> Int
alphaIndex c = fromEnum c - 64

alphaScore :: String -> Int
alphaScore = sum . map alphaIndex

totalScore :: [String] -> Int
totalScore names = sum $ zipWith (*) (map alphaScore $ sort names) [1..]

main :: IO ()
main = do
        str <- readFile "/home/zach/code/euler/022/names.txt"
        print $ totalScore $ parse str
$ ghc -O2 -o names names.hs
$ time ./names
real   0m0.009s
user   0m0.008s
sys    0m0.000s

Python

#!/usr/bin/env python
import os
from string import ascii_uppercase

def calculate_score(name, index):
    alpha_score = sum(ascii_uppercase.index(letter)+1 for letter in name)
    return index * alpha_score

def main():
    names_file = open(os.path.join(os.path.dirname(__file__), 'names.txt'))
    names_string = names_file.read()
    names = [name.strip('"') for name in names_string.split(',')] 
    names.sort()
    print(sum(calculate_score(name, index+1) for index, name in enumerate(names)))
    names_file.close()

if __name__ == "__main__":
    main()
$ time python3 names.py
real   0m0.031s
user   0m0.028s
sys    0m0.000s

Ruby

#!/usr/bin/env ruby

names = File.open(File.dirname(__FILE__) + '/names.txt').read.scan(/\w+/).sort
puts names.map { |name| 
  word_score = name.each_byte.map { |c| c - 64 }.reduce(:+)
  (names.index(name) + 1) * word_score
}.reduce(:+)
$ time ruby names.rb
real   0m0.238s
user   0m0.236s
sys    0m0.000s

Rust

fn main() {
    let mut names: Vec<&str> = include_str!("names.txt").split(',').collect();
    names.sort();
    let sum: usize = names
        .iter()
        .enumerate()
        .map(|(i, name)| {
            let value: usize = name.chars()
                .skip(1)
                .take(name.len() - 2)
                .map(|c| 1 + (c as usize) - ('A' as usize))
                .sum();
            (i + 1) * value
        })
        .sum();
    println!("{}", sum);
}
$ rustc -C target-cpu=native -C opt-level=3 -o names names.rs
$ time ./names
real   0m0.002s
user   0m0.000s
sys    0m0.000s