Skip to content

Instantly share code, notes, and snippets.

@danielpcox
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpcox/40efc6d40c19cf83bf2f to your computer and use it in GitHub Desktop.
Save danielpcox/40efc6d40c19cf83bf2f to your computer and use it in GitHub Desktop.
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