Skip to content

Instantly share code, notes, and snippets.

@adamwespiser
Created January 26, 2012 20:32
Show Gist options
  • Save adamwespiser/1684927 to your computer and use it in GitHub Desktop.
Save adamwespiser/1684927 to your computer and use it in GitHub Desktop.
4clojure problem 44: rotate a sequence
; rotate a sequence
(fn [index col]
(letfn [(rotate [index col]
(nth (iterate #(concat (rest %) (list (first %))) col) index))]
(if (> index 0)
(rotate index col)
(reverse (rotate (* -1 index) (reverse col))))))
;other solutions:
;beickhoff's
(fn rotate [n xs]
(let [length (count xs)
n* (mod n length)]
(concat (drop n* xs) (take n* xs))))
;maximental's solution:
(fn [n x]
(take (count x)
(drop (mod n (count x))
(cycle x))))
;malvert's solution:
(fn [n seq]
(let [k (mod n (count seq))]
(concat (drop k seq) (take k seq))))
;shockbob's solution:
#(let [
[l r] (split-at (mod % (count %2)) %2)]
(concat r l))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment