2009년 2월 17일 화요일

haskell 로 프로젝트 오일러의 22번 문제를 풀어봤다

-- http://projecteuler.net/index.php?section=problems&id=22

import Data.List(sort)
import Data.Char(ord)

-- 으험.. 스플릿 함수가 안보이네. 직접 만들어봤는데 좀 추해보인다.
split :: Char -> String -> [String]
split c s = split' [] s
where split' acc [] = acc
split' acc s = let (tok, remains) = break (==c) s
in split' (tok:acc) (safeTail remains)
safeTail [] = []
safeTail x = tail x

-- 문자열들을 받아서 , 로 스플릿 하고 앞뒤에서 한글자씩 잘라냈다.
-- 따옴표 제거
names s = map (tail . init) $ split ',' s

nth x = (ord x) - (ord 'A') + 1 -- 'A' 에서 몇번째 문자냐
scoreName = sum . map nth -- 이름의 점수
scoreIndexedName (name,index) = (scoreName name) * index -- 점수에 인덱스 곱

solve input =
let splitted = names input -- 쪼개고
sorted = sort splitted -- 정렬하고
indexed = zip sorted [1..] -- 인덱스붙여서
scores = map scoreIndexedName indexed -- 점수내고
in sum scores --

main = do
input <- readFile "/tmp/h/names.txt"
print $ solve input

댓글 없음: