Created
January 26, 2014 20:21
-
-
Save wunki/8638931 to your computer and use it in GitHub Desktop.
Most simple form of string compression.
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
(defn string-compression | |
"Compresses a string by appending the count after the repeat of each | |
letter. For example: \"aabccccaaa\" would become \"a2b1c4a3\". | |
If the compressed string is larger than the original, it should return the | |
original." | |
[s] | |
(let [cnt-orig (count s) | |
compress-fn (fn [coll c] | |
(if (empty? coll) | |
[c 1] | |
(let [last-char (first (take-last 2 coll)) | |
last-count (last coll)] | |
(if (= last-char c) | |
(conj (into [] (butlast coll)) (inc last-count)) | |
(conj coll c 1))))) | |
compressed (str/join (reduce compress-fn [] s))] | |
(if (> (count compressed) (count s)) | |
s | |
compressed))) |
the-kenny
commented
Jan 26, 2014
Test cases:
((fn [in] (min-key count in (reduce #(str %1 (first %2) (count %2)) "" (partition-by identity in)))) "abcdef")
=> "abcdef"
((fn [in] (min-key count in (reduce #(str %1 (first %2) (count %2)) "" (partition-by identity in)))) "aabccccaaa")
=> "a2b1c4a3"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment