Created
July 25, 2011 21:42
-
-
Save DeTeam/1105303 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List | |
import Data.List.Split | |
import Data.Maybe | |
import Data.Char | |
{- | |
http://projecteuler.net/index.php?section=problems&id=22 | |
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? | |
-} | |
getNamesAZ :: [Char] -> [String] | |
getNamesAZ text = f names | |
where | |
names = splitOn "," text | |
f = sort . map read | |
getLetterScore :: Char -> Int | |
getLetterScore x = (ord x) - 64 | |
getNameScore :: [String] -> String -> Int | |
getNameScore names name = nameWeight * lettersWeight | |
where | |
f acc x = acc + (getLetterScore x) | |
index = elemIndex name names | |
nameWeight = (fromJust index) + 1 | |
lettersWeight = foldl f 0 name | |
getTotalNameScore :: [String] -> Int | |
getTotalNameScore names = foldl f 0 names | |
where | |
f acc name = acc + (getNameScore names name) | |
main = do | |
text <- readFile "names.txt" | |
print $ f text | |
where | |
f names = getTotalNameScore . getNamesAZ $ names | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment