Skip to content

Instantly share code, notes, and snippets.

@noughtmare
Last active August 31, 2020 20:29
Show Gist options
  • Select an option

  • Save noughtmare/dbfa0da676e62cb54602d6d448d2891e to your computer and use it in GitHub Desktop.

Select an option

Save noughtmare/dbfa0da676e62cb54602d6d448d2891e to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Data.ByteString.Char8 as B
import System.IO
import Data.List
import qualified Data.Vector as V
import Data.Foldable
generateWords :: [B.ByteString] -> B.ByteString -> [B.ByteString]
generateWords dictionary letters = filter wordMatches dictionary
where
wordMatches :: B.ByteString -> Bool
wordMatches word = B.all (letterCountMatches word) word
letterCountMatches word letter = letter == '\r' || B.count letter word <= B.count letter letters
scores :: V.Vector Int
scores = V.fromList [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]
totalScore :: B.ByteString -> Int
totalScore word = sum (map score (B.unpack word))
score :: Char -> Int
score letter = maybe 0 id (scores V.!? (fromEnum letter - fromEnum 'a'))
sortByScore :: [B.ByteString] -> [B.ByteString]
sortByScore = sortOn totalScore
showResults :: [B.ByteString] -> IO ()
showResults words = traverse_ B.putStrLn $ zipWith showWord [length words, length words - 1 .. 0] words
where
showWord num word = B.pack (show num) <> ". " <> word
main :: IO ()
main = do
putStr "Letters: "
hFlush stdout
letters <- B.getLine
dictionary <- B.readFile "dictionary.txt"
showResults $ sortByScore $ generateWords (B.lines dictionary) letters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment