Finding anagrams for a given word

后端 未结 12 1061
温柔的废话
温柔的废话 2020-12-04 07:43

Two words are anagrams if one of them has exactly same characters as that of the another word.

Example : Anagram & Nagaram are anagrams

12条回答
  •  孤城傲影
    2020-12-04 08:24

    • Reduce the words to - say - lower case (clojure.string/lower-case).
    • Classify them (group-by) by letter frequency-map (frequencies).
    • Drop the frequency maps,
    • ... leaving the collections of anagrams.

    (These) are the corresponding functions in the Lisp dialect Clojure.

    The whole function can be expressed so:

    (defn anagrams [dict]
      (->> dict
           (map clojure.string/lower-case)
           (group-by frequencies)
           vals))
    

    For example,

    (anagrams ["Salt" "last" "one" "eon" "plod"])
    ;(["salt" "last"] ["one" "eon"] ["plod"])
    

    An indexing function that maps each thing to its collection is

    (defn index [xss]
      (into {} (for [xs xss, x xs] [x xs])))
    

    So that, for example,

    ((comp index anagrams) ["Salt" "last" "one" "eon" "plod"])
    ;{"salt" ["salt" "last"], "last" ["salt" "last"], "one" ["one" "eon"], "eon" ["one" "eon"], "plod" ["plod"]}
    

    ... where comp is the functional composition operator.

提交回复
热议问题