Open kimpro82 opened 1 year ago
; Load the Morse code table from a JSON file.
(def morse-code-table (load-file "morse_code.json"))
; Function to convert text to Morse code.
(defn text-to-morse [text]
(let [text-upper (clojure.string/upper-case text)] ; Convert to uppercase
(reduce
(fn [acc char]
(if (contains? morse-code-table char)
(str acc " " (morse-code-table char))
acc))
""
text-upper)))
; Function to convert Morse code to text.
(defn morse-to-text [morse-code]
(let [code-list (clojure.string/split morse-code #" +")]
(->> code-list
(map #(key (first (filter #(= % (val %2)) morse-code-table))))
(apply str))))
; Testing
(println (text-to-morse "HELLO")) ; ".... . .-.. .-.. ---"
(println (morse-to-text ".... . .-.. .-.. ---")) ; "HELLO"
; Load the Morse code table from a JSON file.
(def morse-code-table (load-file "morse_code.json"))
; Function to check if a string is in Morse code.
(defn is-morse? [text]
(re-matches #"(^[-./ ]+$)" text)) ; Check for Morse code pattern
; Function to convert a string to Morse code or vice versa.
(defn convert-text [text]
(let [text-upper (clojure.string/upper-case text)] ; Convert to uppercase
(if (is-morse? text) ; If it's Morse code
(let [code-list (clojure.string/split text #" +")]
(->> code-list
(map #(key (first (filter #(= % (val %2)) morse-code-table))))
(apply str)))
; If it's not Morse code, convert to Morse code
(reduce
(fn [acc char]
(if (contains? morse-code-table char)
(str acc " " (morse-code-table char))
acc))
""
text-upper))))
; Testing
(println (convert-text "HELLO")) ; ".... . .-.. .-.. ---"
(println (convert-text ".... . .-.. .-.. ---")) ; "HELLO"
by ChatGPT