September 18, 2018

Exercism - Run Length Encoding

There are lots of different ways to approach every exercise on Exercism. Why not see how others have solved it?


Implement run-length encoding and decoding.

Run-length encoding (RLE) is a simple form of data compression, where runs (consecutive data elements) are replaced by just one data value and count.

For example we can represent the original 53 characters with only 13.




RLE allows the original data to be perfectly reconstructed from the compressed data, which makes it a lossless data compression.




For simplicity, you can assume that the unencoded string will only contain the letters A through Z (either lower or upper case) and whitespace. This way data to be encoded will never contain any numbers and numbers inside data to be decoded always represent the count for the following character.


First version using partition and a very intricate match of operations to decode the operands. Date: 2018-09-17

(ns run-length-encoding)

(defn run-length-encode
  "encodes a string with run-length-encoding"
  (apply str (map #(clojure.string/replace (str (count %) (first %)) #"1" "")
                  (partition-by identity plain-text)))

(defn better-int? [s]
  (string? (re-find #"\d+" s)))

(defn run-length-decode
  "decodes a run-length-encoded string"
  (apply str (flatten (map-indexed (fn [idx, vl]
                                     (if (better-int? (str vl))
                                       (repeat (- (Integer. (str vl)) 1) (nth cipher-text (+ 1 (Integer. (str idx)))))
                                       vl)) cipher-text))))

This one looks definitely not simple to grasp at first. I need to refactor it. i think the encode operation was just done in a very good way, but the decode is not good at all.

Link to solution at Exercism: Link

Tags: clojure exercism