Skip to content

Commit

Permalink
Implement Clojure solutions and tests for chapter 1, question 5
Browse files Browse the repository at this point in the history
Nitin Punjabi committed Jul 6, 2014
1 parent e7bea9f commit da72a79
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions clojure/chapter01/01_05.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
; Clojure solution to question 1.5 from Cracking the Coding Interview, 5th Edition.
; Nitin Punjabi
; github.com/nitinpunjabi
; nitin@patternhatch.com
(ns chapter01.01-05
(:require [clojure.test :as t]))

(defn compress [s]
(let [parts (partition-by identity s)
compressed-str (clojure.string/join (reduce #(conj % (first %2) (count %2)) [] parts))]
(if (<= (count s) (count compressed-str))
s
compressed-str)))

(t/deftest compression-results
(t/is (= (compress "aabcccccaaa") "a2b1c5a3"))
(t/is (= (compress "aabc aaa") "a2b1c1 4a3"))
(t/is (= (compress "abc") "abc"))
(t/is (= (compress "a") "a"))
(t/is (= (compress "") "")))

0 comments on commit da72a79

Please sign in to comment.