Skip to content

Instantly share code, notes, and snippets.

@wunki
Created January 26, 2014 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wunki/8638931 to your computer and use it in GitHub Desktop.
Save wunki/8638931 to your computer and use it in GitHub Desktop.
Most simple form of string compression.
(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
Copy link

(fn [in] (min-key count in (reduce #(str %1 (first %2) (count %2))  "" (partition-by identity in))))

@the-kenny
Copy link

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