Skip to content

Instantly share code, notes, and snippets.

@lgastako
Created August 31, 2020 22:13
Show Gist options
  • Save lgastako/34e301a8cee023d269325ae7b0768bba to your computer and use it in GitHub Desktop.
Save lgastako/34e301a8cee023d269325ae7b0768bba to your computer and use it in GitHub Desktop.
module Scrabble where
import Data.List ( sortOn )
import Data.Map.Strict ( Map )
import qualified Data.Map.Strict as Map
import System.IO ( hFlush
, stdout
)
main :: IO ()
main = do
dictionary <- lines <$> readFile "dictionary.txt"
putStr "Letters: "
hFlush stdout
letters <- getLine
showResults
. sortOn totalScore
. generateWords dictionary
$ letters
showResults :: [String] -> IO ()
showResults ws = putStr . concatMap showWord . zip ws . countDownFrom . length $ ws
where
showWord (w, n) = show n ++ ". " ++ w ++ "\n"
generateWords :: [String] -> String -> [String]
generateWords dictionary letters = filter (all =<< letterCountMatches) dictionary
where
letterCountMatches w l = l == '\r' || countIn l w <= countIn l letters
totalScore :: String -> Int
totalScore = sum . map score
score :: Char -> Int
score = flip (Map.findWithDefault 0) scores
scores :: Map Char Int
scores = Map.fromList . zip ['a'..'z']
$ [1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10]
countIn :: Eq a => a -> [a] -> Int
countIn v = length . filter (== v)
countDownFrom :: Int -> [Int]
countDownFrom n = enumFromThenTo n (n-1) 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment