Last active
August 29, 2015 14:09
-
-
Save m-renaud/4e7c4dd3fd2cc3644d6b to your computer and use it in GitHub Desktop.
Find words in the English language that can be made with the characters given on the command line.
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
-- This version runs in ~0.7 seconds due to String actually being a linked list | |
-- of Char. Not super efficient. | |
main = do | |
chars <- head <$> getArgs | |
englishWords <- words <$> readFile "en.txt" | |
mapM_ putStrLn $ sortBy (comparing length) $ findValidWords chars englishWords | |
findValidWords :: String -> [String] -> [String] | |
findValidWords chars englishWords = filter (`canBeMadeWith` chars) englishWords | |
canBeMadeWith :: String -> String -> Bool | |
str `canBeMadeWith` cs = all hasValidCount str | |
where hasValidCount c = (occurrences c str) <= (occurrences c cs) | |
occurrences :: Char -> String -> Int | |
occurrences c = length . elemIndices c | |
-- For this version you need to import ByteStream, and we import the functions | |
-- from it with the prefix L so they don't interfere. A ByteStream is a packed | |
-- array of Chars and is much more efficient. This version runs in ~0.15s and | |
-- the only change is having to call L.pack to convert the chars to a ByteStream | |
-- and to use the ByteStream version of the functions. | |
import qualified Data.ByteString.Char8 as L | |
main = do | |
chars <- L.pack <$> head <$> getArgs | |
englishWords <- L.words <$> L.readFile "en.txt" | |
mapM_ L.putStrLn $ sortBy (comparing L.length) $ findValidWords chars englishWords | |
findValidWords :: L.ByteString -> [L.ByteString] -> [L.ByteString] | |
findValidWords chars englishWords = filter (`canBeMadeWith` chars) englishWords | |
canBeMadeWith :: L.ByteString -> L.ByteString -> Bool | |
str `canBeMadeWith` cs = L.all charHasValidCount str | |
where charHasValidCount c = (occurrences c str) <= (occurrences c cs) | |
occurrences :: Char -> L.ByteString -> Int | |
occurrences c = length . L.elemIndices c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment