June 2018 Update

This commit is contained in:
Ingy döt Net 2018-06-22 20:57:24 +00:00
parent ba8067c3b7
commit 22f33d4004
5278 changed files with 84726 additions and 14379 deletions

View file

@ -1,5 +1,37 @@
(defn permutations [a-set]
(cond (empty? a-set) '(())
(empty? (rest a-set)) (list (apply list a-set))
:else (for [x a-set y (permutations (remove #{x} a-set))]
(cons x y))))
(defn permutation-swaps
"List of swap indexes to generate all permutations of n elements"
[n]
(if (= n 2) `((0 1))
(let [old-swaps (permutation-swaps (dec n))
swaps-> (partition 2 1 (range n))
swaps<- (reverse swaps->)]
(mapcat (fn [old-swap side]
(case side
:first swaps<-
:right (conj swaps<- old-swap)
:left (conj swaps-> (map inc old-swap))))
(conj old-swaps nil)
(cons :first (cycle '(:left :right)))))))
(defn swap [v [i j]]
(-> v
(assoc i (nth v j))
(assoc j (nth v i))))
(defn permutations [n]
(let [permutations (reduce
(fn [all-perms new-swap]
(conj all-perms (swap (last all-perms)
new-swap)))
(vector (vec (range n)))
(permutation-swaps n))
output (map vector
permutations
(cycle '(1 -1)))]
output))
(doseq [n [2 3 4]]
(dorun (map println (permutations n))))