Skip to content

Instantly share code, notes, and snippets.

@djtrack16
Created January 13, 2015 02:18
Show Gist options
  • Save djtrack16/bf0e3e6507b016696f78 to your computer and use it in GitHub Desktop.
Save djtrack16/bf0e3e6507b016696f78 to your computer and use it in GitHub Desktop.
given a string and rank, find the permutation is at that index of the sorted permutations
(fn [s rank]
(let [n (count s) step (reduce * (range 1 n))]
(loop [i 0 s (sort s) acc '() r rank step step]
(let [index (quot r step)]
(if (= 1 (count s))
(clojure.string/join (concat acc s))
(recur (inc i)
(concat (take index s) (drop (inc index) s))
(concat acc [(nth s index)])
(- r (* index step))
(quot step (- n (inc i)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment