Last active
March 13, 2018 21:31
-
-
Save russelldavies/a9b0d749240a3a66afbda67c4a57afc4 to your computer and use it in GitHub Desktop.
Anagram Solver
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
module Main exposing (..) | |
import Char | |
import Dict exposing (Dict) | |
createMap : String -> Dict Int (List String) -> Dict Int (List String) | |
createMap word dict = | |
let | |
key = | |
word |> String.toList |> List.sort |> List.map String.fromChar |> String.concat | |
update word = | |
word :: (Dict.get key dict |> Maybe.withDefault []) | |
in | |
Dict.update key (always (Just (update word))) dict | |
anagrams : List String -> List (List String) | |
anagrams words = | |
List.foldr createMap Dict.empty words |> Dict.values | |
main = | |
anagrams [ "foo", "enlist", "bar", "listen", "silent" ] -- [["bar"],["foo"],["enlist","listen","silent"]] |
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
module Main where | |
import Data.Char (ord, toLower) | |
import qualified Data.Map as Map | |
import Data.List (sort) | |
createMap :: String -> Map.Map String [String] -> Map.Map String [String] | |
createMap word map = | |
let | |
key = sort word | |
update word = word : Map.findWithDefault [] key map | |
in | |
Map.alter (const (Just (update word))) key map | |
anagrams :: Foldable t => t String -> [[String]] | |
anagrams words = | |
Map.elems $ foldr createMap Map.empty words | |
main = do | |
wordList <- getContents | |
mapM print $ anagrams $ words wordList | |
-- Pass the word list into the program via stdin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment