Created
February 14, 2021 16:48
-
-
Save watofundefined/cd27f4afc8b447e9ac70da110f3c4c1a to your computer and use it in GitHub Desktop.
This file contains 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
;; 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