Skip to content

Instantly share code, notes, and snippets.

@zaneli
Last active August 29, 2015 13:59
Show Gist options
  • Save zaneli/10540895 to your computer and use it in GitHub Desktop.
Save zaneli/10540895 to your computer and use it in GitHub Desktop.
「ClojureでNinety-Nine Lisp Problems(P11~15)」ブログ用
(defn my-encode
"Run-length encoding of a list."
[xs]
(map #(list (count %) (first %)) (partition-by identity xs))
)
(defn my-encode-modified
"Modified run-length encoding."
[xs]
(map #(let [[cnt elem] %] (if (== cnt 1) elem (list cnt elem))) (my-encode xs))
)
(defn my-decode
"Decode a run-length encoded list."
[xs]
(flatten (map #(if (list? %) (replicate (first %) (second %)) %) xs))
)
(defn my-decode
"Decode a run-length encoded list."
[xs]
(reduce #(concat %1 (if (list? %2) (replicate (first %2) (second %2)) (list %2))) nil xs)
)
(defn my-encode-direct
"Run-length encoding of a list (direct solution)."
[xs]
(reverse (loop [[x & _ :as xs] xs, ys nil]
(if (nil? x)
ys
(let [[[e & _ :as z] zs] (split-with #(= x %) xs),
cnt (count z),
elem (if (== cnt 1) e (list cnt e))]
(recur zs (cons elem ys))
)
)
))
)
(defn my-encode-direct
"Run-length encoding of a list (direct solution)."
[xs]
(map
#(let [cnt (count %), elem (first %)]
(if (== cnt 1) elem (list cnt elem))
)
(partition-by identity xs)
)
)
(defn my-dupli
"Duplicate the elements of a list."
[xs]
(reduce #(concat %1 (replicate 2 %2)) nil xs)
)
(defn my-repli
"Replicate the elements of a list a given number of times."
[xs n]
(reduce #(concat %1 (replicate n %2)) nil xs)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment