Skip to content

Instantly share code, notes, and snippets.

@watofundefined
Created February 14, 2021 16:48
Show Gist options
  • Save watofundefined/cd27f4afc8b447e9ac70da110f3c4c1a to your computer and use it in GitHub Desktop.
Save watofundefined/cd27f4afc8b447e9ac70da110f3c4c1a to your computer and use it in GitHub Desktop.
;; Inspired by:
;; https://danielbmarkham.com/fun-with-an-interview-question/
;; https://github.com/smcl/LetterSequencer/blob/master/Interview.LetterSequencer.FSharp/Program.fs
(defn run-length-encode
"Accepts a string (or any seq of characters).
Returns its encoded representation as a seq of char-count tuples.
Example: (aaabb ~> [[a 3][b 2]])"
([s]
(run-length-encode s []))
([s encoded]
(if (empty? s)
encoded
(let [[matched rest] (split-with #{(first s)} s)]
(recur rest (conj encoded [(first s) (count matched)]))))))
(defn run-length-decode
"Accepts a seq of char-count tuples, returns a string ([[\a 2] [\b 1]] ~> aab)"
[codes]
(reduce
(fn [s [ch n]]
(str s (str/join (repeat n ch))))
""
codes))
(comment
(run-length-encode "aaaabbbcca")
(run-length-decode (run-length-encode "aaaabbbcca"))
(run-length-decode []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment