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?

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
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 = [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()
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