Skip to content

Instantly share code, notes, and snippets.

@ha2ne2
Last active September 9, 2017 14:01
Show Gist options
  • Save ha2ne2/4726c9b938a0a3dbc047051157dbcd54 to your computer and use it in GitHub Desktop.
Save ha2ne2/4726c9b938a0a3dbc047051157dbcd54 to your computer and use it in GitHub Desktop.
(defn iterate* [f x]
(if (nil? x) nil
(cons x (lazy-seq (iterate* f (f x))))))
(defn iter-perm [v]
(let [len (count v)
left (loop [i (- len 2)]
(cond (< i 0) nil
(< (v i) (v (inc i))) i
:else (recur (dec i))))]
(when left
(let [vl (v left)
right (loop [i (dec len)]
(if (< vl (v i)) i (recur (dec i))))]
(loop [v (assoc v left (v right) right (v left)) left (inc left) right (dec len)]
(if (< left right)
(recur (assoc v left (v right) right (v left)) (inc left) (dec right))
v))))))
; (map #(apply str %) (take 10 (permutations "Permtation of Ruby")))
;; ("Permtation of Ruby"
;; "Permtation of Ruyb"
;; "Permtation of Rbuy"
;; "Permtation of Rbyu"
;; "Permtation of Ryub"
;; "Permtation of Rybu"
;; "Permtation of uRby"
;; "Permtation of uRyb"
;; "Permtation of ubRy"
;; "Permtation of ubyR")
(defn permutations [lst]
(let [v (vec lst)]
(map #(map v %) (iterate* iter-perm (vec (range (count lst)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment