Run-length encoding: Difference between revisions

Content added Content deleted
(→‎{{header|J}}: simplify and speed up rle)
(added Clojure version)
Line 340: Line 340:


'''Final note''': since the repeat counter value 0 has no meaning, it could be used as it would be 256, so extending by one the maximum number of repetitions representable with a single byte; or instead it could be used as a special marker to encode in a more efficient way (long) sequences of ''isolated characters'', e.g. "ABCDE" would be encoded as "1A1B1C1D1E"; it could be instead encoded as "05ABCDE".
'''Final note''': since the repeat counter value 0 has no meaning, it could be used as it would be 256, so extending by one the maximum number of repetitions representable with a single byte; or instead it could be used as a special marker to encode in a more efficient way (long) sequences of ''isolated characters'', e.g. "ABCDE" would be encoded as "1A1B1C1D1E"; it could be instead encoded as "05ABCDE".

=={{header|Clojure}}==
<lang clojure>
(defn step [[result, n, c], new] ;function used in encode's reduce call
(cond
(zero? n) [result, 1, new]
(= c new) [result, (inc n), c]
:else [(conj result [n c]), 1, new]))

(defn encode [s]
(let [[result,n,chr] (reduce step [[],0,nil] s)]
(if (= n 0)
result
(conj result [n chr]))))

(defn decode [v]
(let [expand (fn [[n c]] (repeat n c))]
(apply str (mapcat expand v))))
</lang>
<lang clojure>
(def uncoded "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
(def coded [[12 \W] [1 \B] [12 \W] [3 \B] [24 \W] [1 \B] [14 \W]])

(assert (= (encode uncoded) coded))
(assert (= (decode coded) uncoded))
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==