kimpro82 / MyPractice

Born in October and learn like octopus
0 stars 0 forks source link

Clojure : Morse Code Converter #283

Open kimpro82 opened 1 year ago

kimpro82 commented 12 months ago

by ChatGPT

{
  "A": ".-",    "N": "-.",    "0": "-----",
  "B": "-...",  "O": "---",   "1": ".----",
  "C": "-.-.",  "P": ".--.",  "2": "..---",
  "D": "-..",   "Q": "--.-",  "3": "...--",
  "E": ".",     "R": ".-.",   "4": "....-",
  "F": "..-.",  "S": "...",   "5": ".....",
  "G": "--.",   "T": "-",     "6": "-....",
  "H": "....",  "U": "..-",   "7": "--...",
  "I": "..",    "V": "...-",  "8": "---..",
  "J": ".---",  "W": ".--",   "9": "----.",
  "K": "-.-",   "X": "-..-",
  "L": ".-..",  "Y": "-.--",
  "M": "--",    "Z": "--.."
}
kimpro82 commented 12 months ago

by ChatGPT

; 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"
kimpro82 commented 12 months ago

by ChatGPT

; 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"