-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
permute.cljc
256 lines (226 loc) · 8.9 KB
/
permute.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#_"SPDX-License-Identifier: GPL-3.0"
(ns sicmutils.util.permute
"Utilities for generating permutations of sequences."
(:require [sicmutils.special.factorial :as sf]
#?(:cljs [sicmutils.generic :as g]))
#?(:clj
(:import (clojure.lang APersistentVector))))
(defn ^:no-doc delete-nth
"returns the sequence `xs` with its `n`th element dropped."
[xs n]
(concat (take n xs)
(drop (inc n) xs)))
(defn permutations
"Returns a lazy sequence of every possible arrangement of the elements of `xs`."
[xs]
(if (empty? xs)
'(())
(letfn [(f [i item]
(map (fn [perm]
(cons item perm))
(permutations
(delete-nth xs i))))]
(sequence (comp (map-indexed f) cat)
xs))))
(defn combinations
"Returns a lazy sequence of every possible set of `p` elements chosen from
`xs`."
[xs p]
(cond (zero? p) '(())
(empty? xs) ()
:else (concat
(map (fn [more]
(conj more (first xs)))
(combinations (rest xs)
(dec p)))
(combinations (rest xs) p))))
(defn cartesian-product
"Accepts a sequence of collections `colls` and returns a lazy sequence of the
cartesian product of all collections.
The cartesian product of N collections is a sequences of sequences, each `N`
long, of every possible way of choosing `N` items where the first comes from
the first entry in `colls`, the second from the second entry and so on.
NOTE: This implementation comes from Alan Malloy at this [StackOverflow
post](https://stackoverflow.com/a/18248031). Thanks, Alan!"
[colls]
(if (empty? colls)
'(())
(for [more (cartesian-product (rest colls))
x (first colls)]
(cons x more))))
(defn list-interchanges
"Given a `permuted-list` and the `original-list`, returns the number of
interchanges required to generate the permuted list from the original list."
[permuted-list original-list]
(letfn [(lp1 [plist n]
(if (empty? plist)
n
(let [fp (first plist)
bigger (rest (drop-while #(not= % fp) original-list))
more (rest plist)]
(lp2 n bigger more more 0))))
(lp2 [n bigger more l increment]
(if (empty? l)
(lp1 more (+ n increment))
(lp2 n bigger more
(rest l)
(if-not (some #{(first l)} bigger)
(inc increment)
increment))))]
(lp1 permuted-list 0)))
(defn permutation-interchanges [permuted-list]
(letfn [(lp1 [plist n]
(if (empty? plist)
n
(let [[x & xs] plist]
(lp2 n x xs xs 0))))
(lp2 [n x xs l increment]
(if (empty? l)
(lp1 xs (+ n increment))
(lp2 n x xs
(rest l)
(if (>= (first l) x)
increment
(inc increment)))))]
(lp1 permuted-list 0)))
(defn- same-set?
"Returns true if `x1` and `x2` contain the same elements, false otherwise."
[x1 x2]
(= (sort-by hash x1)
(sort-by hash x2)))
(defn permutation-parity
"If a single `permuted-list` is supplied, returns the parity of the number of
interchanges required to sort the permutation.
NOTE that the requirement that elements be sortable currently constrains
`permuted-list`'s elements to be numbers that respond to `>=`.
For two arguments, given a `permuted-list` and the `original-list`, returns
the parity (1 for even, -1 for odd) of the number of the number of
interchanges required to generate the permuted list from the original list.
In the two-argument case, if the two lists aren't permutations of each other,
returns 0."
([permuted-list]
(let [swaps (permutation-interchanges permuted-list)]
(if (even? swaps) 1 -1)))
([permuted-list original-list]
(if (and (= (count permuted-list)
(count original-list))
(same-set? permuted-list original-list))
(if (even? (list-interchanges permuted-list original-list))
1
-1)
0)))
(defn permute
"Given a `permutation` (represented as a list of numbers), and a sequence `xs`
to be permuted, construct the list so permuted."
[permutation xs]
(let [xs (vec xs)]
(map (fn [p] (get xs p))
permutation)))
(defn- index-of [v x]
#?(:clj (.indexOf ^APersistentVector v x)
:cljs (#'-indexOf v x)))
(defn sort-and-permute
"cont = (fn [ulist slist perm iperm] ...)
Given a short list and a comparison function, to sort the list by the
comparison, returning the original list, the sorted list, the permutation
procedure and the inverse permutation procedure developed by the sort."
[ulist <? cont]
(let [n (count ulist)
lsource (map vector ulist (range n))
ltarget (sort-by first (comparator <?) lsource)
sorted (mapv first ltarget)
perm (mapv second ltarget)
iperm (map (fn [i] (index-of perm i))
(range n))]
(cont ulist
sorted
(fn [l] (permute perm l))
(fn [l] (permute iperm l)))))
;; Sometimes we want to permute some of the elements of a list, as follows:
(defn subpermute
"Given a sequence `xs` and a map `m` of replacement indices, returns a new
version of `xs` with the element at the position marked by each key in `m`
replaced by the element at each value in the original `xs`."
[m xs]
(reduce-kv (fn [acc k v]
(assoc acc k (get xs v)))
xs
m))
(defn number-of-permutations
"Returns the number of possible ways of permuting a collection of `n` distinct
elements."
[n]
(sf/factorial n))
(defn number-of-combinations
"Returns 'n choose k', the number of possible ways of choosing `k` distinct
elements from a collection of `n` total items."
[n k]
{:pre [(>= n 0)]}
(sf/binomial-coefficient n k))
(let [div #?(:clj / :cljs g//)]
(defn multichoose
"Returns the number of possible ways of choosing a multiset with cardinality `k`
from a set of `n` items, where each item is allowed to be chosen multiple
times."
[n k]
{:pre [(>= n 0) (>= k 0)]}
(if (zero? k)
1
(div (sf/rising-factorial n k)
(sf/factorial k)))))
(defn permutation-sequence
"Produces an iterable sequence developing the permutations of the input sequence
of objects (which are considered distinct) in church-bell-changes order - that
is, each permutation differs from the previous by a transposition of adjacent
elements (Algorithm P from §7.2.1.2 of Knuth).
This is an unusual way to go about this in a functional language, but it's
fun.
This approach has the side-effect of arranging for the parity of the generated
permutations to alternate; the first permutation yielded is the identity
permutation (which of course is even).
Inside, there is a great deal of mutable state, but this cannot be observed by
the user."
[as]
(let [n (count as)
a (object-array as)
c (int-array n (repeat 0)) ;; P1. [Initialize.]
o (int-array n (repeat 1))
return #(into [] %)
the-next (atom (return a))
has-next (atom true)
;; step implements one-through of algorithm P up to step P2,
;; at which point we return false if we have terminated, true
;; if a has been set to a new permutation. Knuth's code is
;; one-based; this is zero-based.
step (fn [j s]
(let [q (int (+ (aget c j) (aget o j)))] ;; P4. [Ready to change?]
(cond (< q 0)
(do ;; P7. [Switch direction.]
(aset o j (int (- (aget o j))))
(recur (dec j) s))
(= q (inc j))
(if (zero? j)
false ;; All permutations have been delivered.
(do (aset o j (int (- (aget o j)))) ;; P6. [Increase s.]
(recur (dec j) (inc s)))) ;; P7. [Switch direction.]
:else ;; P5. [Change.]
(let [i1 (+ s (- j (aget c j)))
i2 (+ s (- j q))
t (aget a i1)
]
(aset a i1 (aget a i2))
(aset a i2 t)
(aset c j q)
true ;; More permutations are forthcoming.
))))]
(#?(:clj iterator-seq :cljs #'cljs.core/chunkIteratorSeq)
(reify #?(:clj java.util.Iterator :cljs Object)
(hasNext [_] @has-next)
(next [_] ;; P2. [Visit.]
(let [prev @the-next]
(reset! has-next (step (dec n) 0))
(reset! the-next (return a))
prev))
#?@(:cljs
[IIterable
(-iterator [this] this)])))))