(defn rotate [a n]
(let [l (count a)
off (mod (+ (mod n l) l) l)]
(flatten (list (drop off a) (take off a)))))
(rotate '(1 2 3 4 5) -1) => (5 1 2 3 4)
(rotate '(1 2 3 4 5) -6) => (5 1 2 3 4)
(rotate '(1 2 3 4 5) 3) => (4 5 1 2 3)
(rotate '(1 2 3 4 5) 103) => (4 5 1 2 3)
(rotate '(1 2 3 4 5) 2) => (3 4 5 1 2)
(rotate '(1 2 3 4 5) 7) => (3 4 5 1 2)
Rotates any number of times
Handles zero with no conditional
n can be larger than the length and it will map correctly
Negative n rotates right, Positive n rotates left
On Thursday, April 22, 2010 at 9:13:52 AM UTC-6, Sean Devlin wrote:
>
> Oh wow... totally would have :)
>
> On Apr 21, 8:16 pm, Harvey Hirst <[email protected]> wrote:
> > > (defn rotate [n s]
> > > (let [[front back] (split-at (mod n (count s)) s)]
> > > (concat back front)))
> >
> > Don't forget (mod n 0) is an ArithmeticException.
> >
> > Harvey
> >
> > --
> > You received this message because you are subscribed to the Google
> > Groups "Clojure" group.
> > To post to this group, send email to [email protected]
> <javascript:>
> > Note that posts from new members are moderated - please be patient with
> your first post.
> > To unsubscribe from this group, send email to
> > [email protected] <javascript:>
> > For more options, visit this group athttp://
> groups.google.com/group/clojure?hl=en
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected] <javascript:>
> Note that posts from new members are moderated - please be patient with
> your first post.
> To unsubscribe from this group, send email to
> [email protected] <javascript:>
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.