Skip to content

Instantly share code, notes, and snippets.

@danielpcox danielpcox/rotate.clj
Last active Aug 29, 2015

Embed
What would you like to do?
Rotate Sequence
; Solving 4Clojure 44
; first try
(def rotate
(fn [n xs]
(if (= n 0)
xs
(let [nextn (* (dec (Math/abs n)) (if (< n 0) -1 1))
nextxs (and (not= 0 n)
(if (< n 0)
(cons (last xs) (vec (butlast xs)))
(conj (vec (rest xs)) (first xs))))]
(if (= n 0)
xs
(recur nextn nextxs))))))
; better
(defn rotate-better [n xs]
(let [len (count xs)
n (mod n len)
split (if (>= n 0) n (+ n len))]
(concat (drop split xs) (take split xs))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.