Skip to content

Instantly share code, notes, and snippets.

@PEZ
Last active April 30, 2024 23:19
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 PEZ/2a419f3d9e0c22be01179175f6a7d2f0 to your computer and use it in GitHub Desktop.
Save PEZ/2a419f3d9e0c22be01179175f6a7d2f0 to your computer and use it in GitHub Desktop.
Rotate Sequence – Rich 4Clojure Problem 44 – See: https://github.com/PEZ/rich4clojure
(ns rich4clojure.medium.problem-044
(:require [hyperfiddle.rcf :refer [tests]]))
;; = Rotate Sequence =
;; By 4Clojure user: dbyrne
;; Difficulty: Medium
;; Tags: [seqs]
;;
;; Write a function which can rotate a sequence in either
;; direction.
(def __ :tests-will-fail)
(comment
)
(tests
(__ 2 [1 2 3 4 5]) := '(3 4 5 1 2)
(__ -2 [1 2 3 4 5]) := '(4 5 1 2 3)
(__ 6 [1 2 3 4 5]) := '(2 3 4 5 1)
(__ 1 '(:a :b :c)) := '(:b :c :a)
(__ -4 '(:a :b :c)) := '(:c :a :b))
;; To participate, fork:
;; https://github.com/PEZ/rich4clojure
;; Post your solution below, please!
@avillega
Copy link

(defn- rotate [n coll]
  (concat
   (drop n coll)
   (take n coll)))

(defn- rotate-backwards [n coll]
  (concat
   (take-last n coll)
   (drop-last n coll)))

(defn rotate-any-dir [steps coll]
  (let [steps (rem steps (count coll))]
    (if (< steps 0)
      (rotate-backwards (Math/abs steps) coll)
      (rotate steps coll))))

(def __ rotate-any-dir)

(comment
  (mod -4 3)
  ;; normal rotate
  (concat
   (drop 2 [1 2 3 4 5])
   (take 2 [1 2 3 4 5]))
  (rotate 2 [1 2 3 4 5])

  (concat
   (take-last 2 [1 2 3 4 5])
   (drop-last 2 [1 2 3 4 5]))
  
  (rotate-backwards 2 [1 2 3 4 5])

  (rotate-any-dir -4 [1 2 3])
  )

@blogscot
Copy link

(defn __ [n coll]
  (let [length (count coll)]
    (concat (drop (mod n length) coll)
            (take (mod n length) coll))))

@StanTheBear
Copy link

(fn [split-count in-seq]
    "rotate a seq in either direction"
    (apply concat (reverse
           (split-at (mod split-count (count in-seq)) in-seq))))

@onstop4
Copy link

onstop4 commented Mar 13, 2023

(fn [n coll] (let [coll-count (count coll)]
    (take coll-count (drop (mod n coll-count) (cycle coll)))))

@natef-GuruTech
Copy link

(def __ (fn [n xs]
          (let [n' (mod n (count xs))
                movers (take n' xs)]
            (concat (drop n' xs) movers))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment