Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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:
(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
You can’t perform that action at this time.