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]
= words . map replaceComma . filter notQuote where
parse ',' = ' '
replaceComma = c
replaceComma c = (/= '"')
notQuote
alphaIndex :: Char -> Int
= fromEnum c - 64
alphaIndex c
alphaScore :: String -> Int
= sum . map alphaIndex
alphaScore
totalScore :: [String] -> Int
= sum $ zipWith (*) (map alphaScore $ sort names) [1..]
totalScore names
main :: IO ()
= do
main <- readFile "/home/zach/code/euler/022/names.txt"
str print $ totalScore $ parse str
$ ghc -O2 -o names names.hs
$ time ./names
real 0m0.010s
user 0m0.010s
sys 0m0.000s
Python
#!/usr/bin/env python
import os
from string import ascii_uppercase
def calculate_score(name, index):
= sum(ascii_uppercase.index(letter)+1 for letter in name)
alpha_score return index * alpha_score
def main():
= open(os.path.join(os.path.dirname(__file__), 'names.txt'))
names_file = names_file.read()
names_string = [name.strip('"') for name in names_string.split(',')]
names
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.044s
user 0m0.037s
sys 0m0.008s
Ruby
#!/usr/bin/env ruby
= File.open(File.dirname(__FILE__) + '/names.txt').read.scan(/\w+/).sort
names puts names.map { |name|
= name.each_byte.map { |c| c - 64 }.reduce(:+)
word_score .index(name) + 1) * word_score
(names}.reduce(:+)
$ time ruby names.rb
real 0m0.289s
user 0m0.281s
sys 0m0.008s
Rust
fn main() {
let mut names: Vec<&str> = include_str!("names.txt").split(',').collect();
.sort();
nameslet 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();
+ 1) * value
(i })
.sum();
println!("{}", sum);
}
$ rustc -C target-cpu=native -C opt-level=3 -o names names.rs
$ time ./names
real 0m0.004s
user 0m0.000s
sys 0m0.004s