Skip to content

Instantly share code, notes, and snippets.

@russelldavies
Last active March 13, 2018 21:31
Show Gist options
  • Save russelldavies/a9b0d749240a3a66afbda67c4a57afc4 to your computer and use it in GitHub Desktop.
Save russelldavies/a9b0d749240a3a66afbda67c4a57afc4 to your computer and use it in GitHub Desktop.
Anagram Solver
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"]]
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