Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. user=> (require '[clojure.string :as str])
  2. nil
  3. user=> (def dictionary (->> (slurp "/home/arne/Downloads/purely functional - wordlist.txt")
  4. #_=> (str/split-lines)))
  5. #'user/dictionary
  6. user=> (defn frequency-histogram [phrase]
  7. #_=> (->> (str/split (str/lower-case phrase) #"\s+")
  8. #_=> (map frequencies)
  9. #_=> (apply merge-with +)))
  10. #'user/frequency-histogram
  11. user=> (defn fits-perfectly? [p1 p2]
  12. #_=> (->> (merge-with - (frequency-histogram p1) (frequency-histogram p2))
  13. #_=> (vals)
  14. #_=> (every? zero?)))
  15. #'user/fits-perfectly?
  16. user=> (defn fits-in-phrase? [phrase1 phrase2]
  17. #_=> (let [freq1 (frequency-histogram phrase1)
  18. #_=> freq2 (frequency-histogram phrase2)]
  19. #_=> (every? (fn [[k v]]
  20. #_=> (>= (get freq1 k 0) v)) freq2)))
  21. #'user/fits-in-phrase?
  22. user=> (defn find-anagram
  23. #_=> [phrase]
  24. #_=> (let [dictionary (filter (partial fits-in-phrase? phrase) dictionary)]
  25. #_=> (loop [word (nth dictionary 0)
  26. #_=> candidates dictionary
  27. #_=> anagram []
  28. #_=> found []
  29. #_=> next-start 1]
  30. #_=> (cond
  31. #_=> ;; as long as our list of candidates isn't completely used up...
  32. #_=> (some? word)
  33. #_=> (let [guess (str/join " " (conj anagram word))]
  34. #_=> (cond
  35. #_=> ;; found an anagram :)
  36. #_=> (fits-perfectly? phrase guess)
  37. #_=> (recur (first candidates) dictionary anagram (conj found (conj anagram word))
  38. #_=>
  39. #_=> ;; might still find one
  40. #_=> (fits-in-phrase? phrase guess)
  41. #_=> (recur (first candidates) dictionary (conj anagram word) found next-start)
  42. #_=>
  43. #_=> ;; the current word doesn't fit
  44. #_=> :else
  45. #_=> (recur (first candidates) (rest candidates) anagram found next-start)))
  46. #_=>
  47. #_=> ;; try again from a blank anagram if we weren't sucessful
  48. #_=> (< next-start (count dictionary))
  49. #_=> (recur (nth dictionary next-start) dictionary [] found (inc next-start)))
  50. #_=>
  51. #_=> ;; we did everything we could :)
  52. #_=> :else found))))
  53. #'user/find-anagram
  54. ;; TODO: Find all anagrams, not just the first one alphabetically
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement