Last active
May 5, 2022 01:10
-
-
Save rafd/e79b0ed41d9c2495b10581818b20b74b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(ns exercises.core | |
(:require | |
[clojure.walk :as walk])) | |
;; trie | |
; "hello" | |
; "hi" | |
; "he" | |
; h | |
; e | |
; EOW | |
; l | |
; l | |
; o | |
; EOW | |
; i | |
; EOW | |
(def trie | |
{\h {\i {:EOW nil} | |
\e {:EOW nil | |
\l {\l {\o {:EOW nil}}}}}}) | |
(defn all-words [trie] | |
(walk/postwalk (fn [e] | |
(cond | |
(= e nil) [""] | |
(= :EOW e) "" | |
(map? e) (mapcat (fn [[k vs]] | |
(map (fn [v] (str k v)) vs)) | |
e) | |
:else e)) | |
trie)) | |
(defn subtree [trie query] | |
(get-in trie query)) | |
#_(map identity "he") | |
#_(subtree trie "he") | |
(defn autocomplete [trie query] | |
(map (partial str query) (all-words (subtree trie query)))) | |
#_(autocomplete trie "he") | |
(cons "he" ["" "llo"]) | |
["" "llo"] | |
["he" "hello"] | |
(map (partial str "he") ["" "llo"]) | |
(mapcat (fn [[k vs]] | |
(map (fn [v] (str k v)) vs)) | |
{\a ["b" "c"] | |
\d ["e" "f"]}) | |
"ab" "ac" | |
"de" "df" | |
#_(autocomplete trie "he") | |
; #{"hello" "he"} | |
(def words ["hello" "hi" "he"]) | |
(defn trie | |
[words] | |
(reduce (fn [memo word] | |
(assoc-in memo (conj (vec word) :EOW) nil)) | |
{} words)) | |
#_(assoc-in {} [\a \b \c \d \e] nil) | |
#_(trie words) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment