Jump to content

Permutations by swapping: Difference between revisions

(Added C implementation.)
Line 315:
=={{header|Clojure}}==
===Recursive version===
{{incorrect|clojure|More than one swap between successive perms.}}
<lang clojure>
(defn permutations [apermutation-set]swaps
"List of swap indexes to generate all permutations of n elements"
(cond (empty? a-set) '(())
[n]
(empty? (rest a-set)) (list (apply list a-set))
(if (= n 2) `((0 1))
:else (for [x a-set y (permutations (remove #{x} a-set))]
(let [old-swaps (permutation-swaps (cons xdec y))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))))
 
 
user=>(defn (permutations [1 2 3n])
(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))))
</lang>
 
Line 327 ⟶ 358:
 
<pre>
[[0 1] 1]
user=> (permutations [1 2 3])
[[1 0] -1]
((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
[[0 1 2] 1]
user=> (permutations [1 2 3 4])
[[0 2 1] -1]
((1 2 3 4) (1 2 4 3) (1 3 2 4) (1 3 4 2) (1 4 2 3) (1 4 3 2) (2 1 3 4) (2 1 4 3) (2 3 1 4) (2 3 4 1) (2 4 1 3) (2 4 3 1) (3 1 2 4) (3 1 4 2) (3 2 1 4) (3 2 4 1) (3 4 1 2) (3 4 2 1) (4 1 2 3) (4 1 3 2) (4 2 1 3) (4 2 3 1) (4 3 1 2) (4 3 2 1))
[[2 0 1] 1]
user=>
[[2 1 0] -1]
[[1 2 0] 1]
[[1 0 2] -1]
[[0 1 2 3] 1]
[[0 1 3 2] -1]
[[0 3 1 2] 1]
[[3 0 1 2] -1]
[[3 0 2 1] 1]
[[0 3 2 1] -1]
[[0 2 3 1] 1]
[[0 2 1 3] -1]
[[2 0 1 3] 1]
[[2 0 3 1] -1]
[[2 3 0 1] 1]
[[3 2 0 1] -1]
[[3 2 1 0] 1]
[[2 3 1 0] -1]
[[2 1 3 0] 1]
[[2 1 0 3] -1]
[[1 2 0 3] 1]
[[1 2 3 0] -1]
[[1 3 2 0] 1]
[[3 1 2 0] -1]
[[3 1 0 2] 1]
[[1 3 0 2] -1]
[[1 0 3 2] 1]
[[1 0 2 3] -1]
</pre>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.