Last active
March 13, 2019 21:10
-
-
Save JulienRouse/6c36449a604cf373162542806f0e43af to your computer and use it in GitHub Desktop.
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
;Attempt at the puzzle of issue 316 of Eric Normand newsletter. | |
; | |
;Thanks @seancorfield for his help on the clojure slack channel with destructuring parameters in anonymous function | |
;to help clean the code | |
;Run-length encode a sequence | |
;Run-length encoding is a way to represent a sequence in a more compact form. Instead of saying :p :p :p, you say "3 :ps". Write a function that takes a sequence and returns that sequence with run-length encoding. | |
;(rle [:a :a :a :b :c :d :d :d :d]) | |
;=> ([3 :a] [1 :b] [1 :c] [4 :d]) | |
;(rld '([3 :a] [1 :b] [1 :c] [4 :d])) | |
;=> (:a :a :a :b :c :d :d :d :d) | |
;First version | |
(defn rle | |
[seq] | |
(->> seq | |
(partition-by identity) | |
(map #(vec [(count %1) (first %1)])))) | |
(defn rld | |
[pairs] | |
(mapcat (fn [[n val]] (repeat n val)) | |
pairs)) | |
;Another version with tranducers | |
(def xf-rle2 | |
(comp | |
(partition-by identity) | |
(map #(vec [(count %1) (first %1)])))) | |
(defn rle2 | |
[seq] | |
(sequence xf-rle2 seq)) | |
(def xf-rld2 | |
(mapcat (fn [[n val]] (repeat n val)))) | |
(defn rld2 | |
[pairs] | |
(sequence xf-rld2 pairs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment