Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- The utility reads a set of text lines from stdin, selects the
- -- "weightiest" word in each of them and sends it to stdout. The
- -- weight of a word is a sum of weights of its letters; the weight of
- -- each letter roughly corresponds to its average occurence rate. If
- -- applied to this text, the utility outputs the following:
- -- utility
- -- weightiest
- -- weights
- -- corresponds
- -- following
- import Data.Char (ord)
- weightsList :: [Int]
- weightsList =
- [ 3 -- a
- , 20 -- b
- , 12 -- c
- , 9 -- d
- , 1 -- e
- , 16 -- f
- , 18 -- g
- , 8 -- h
- , 5 -- i
- , 24 -- j
- , 22 -- k
- , 11 -- l
- , 14 -- m
- , 6 -- n
- , 4 -- o
- , 19 -- p
- , 25 -- q
- , 10 -- r
- , 7 -- s
- , 2 -- t
- , 13 -- u
- , 21 -- v
- , 15 -- w
- , 23 -- x
- , 17 -- y
- , 26 -- z
- ]
- validCharList :: String
- validCharList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-'… \n"
- charToWeight :: Char -> Int
- charToWeight char
- | charCode > 96 && charCode < 123 = pickCharWeight forLowerCase
- | charCode > 64 && charCode < 91 = pickCharWeight forUpperCase
- | otherwise = 0
- where
- charCode = ord char
- pickCharWeight offset = weightsList !! (charCode - offset)
- forLowerCase = 97
- forUpperCase = 65
- wordToWeight :: String -> Int
- wordToWeight "" = 0
- wordToWeight word = sum $ map charToWeight word
- weightierWord :: String -> String -> String
- weightierWord "" string = string
- weightierWord string "" = string
- weightierWord string1 string2
- | wordToWeight string1 > wordToWeight string2 = string1
- | otherwise = string2
- weightiestWordInList :: [String] -> String
- weightiestWordInList [] = ""
- weightiestWordInList list = foldl1 weightierWord list
- uniqueAdjacentSpaces :: String -> String
- uniqueAdjacentSpaces [] = []
- uniqueAdjacentSpaces [char] = [char]
- uniqueAdjacentSpaces (char1:char2:chars)
- | char1 == ' ' && char2 == ' ' = uniqueAdjacentSpaces (char2 : chars)
- | otherwise = char1 : uniqueAdjacentSpaces (char2 : chars)
- filterChars :: String -> String
- filterChars = filter filterFunction
- where
- filterFunction = flip elem validCharList
- main :: IO ()
- main = do
- input <- getContents
- mapM_
- ((putStrLn . weightiestWordInList) . words)
- (lines $ (uniqueAdjacentSpaces . filterChars) input)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement