Guest User

Untitled

a guest
May 25th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. (ns euler24)
  2.  
  3. (defn permute [coll]
  4. "Returns a lazy sequence of the permutations of coll as cons cells;
  5. each car is the item in the permutation, and each cdr is a sequence
  6. of the tails of the permutations starting with that element. If coll is in
  7. lexicographical order, so are the permutations produced by walking the result of
  8. permute depth-first."
  9. (when-let [s (seq coll)]
  10. (map (fn [x] (cons x (permute (remove #(= x %) s)))) s)))
  11.  
  12. (defn factorial [n]
  13. "Returns n! for positive integer n."
  14. (loop [cnt n acc 1]
  15. (if (<= cnt 0)
  16. acc
  17. (recur (dec cnt) (* acc cnt)))))
  18.  
  19. (defn- seek
  20. ([s parts i acc]
  21. "Seeks to the permutation at index i in permutation sequence s, representing partitions of
  22. parts remaining elements. Accumulates sequence values in acc until desired index is reached."
  23. (if (empty? s) acc
  24. (let [partsize (factorial (dec parts))
  25. permutation (nth s (quot i partsize))
  26. data (first permutation)
  27. remainder (rest permutation)]
  28. (recur remainder (dec parts) (mod i partsize) (conj acc data)))))
  29. ([s parts i] (seek s parts i [])))
  30.  
  31. (defn ith-permutation [n i]
  32. "Generate the ith lexicographical permutation of the numbers from 0..n (inclusive)."
  33. (let [coll (range (inc n))]
  34. (seek (permute coll) (count coll) (dec i))))
Add Comment
Please, Sign In to add comment