diff src/clojure/contrib/combinatorics.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/clojure/contrib/combinatorics.clj	Sat Aug 21 06:25:44 2010 -0400
     1.3 @@ -0,0 +1,164 @@
     1.4 +;;; combinatorics.clj: efficient, functional algorithms for generating lazy
     1.5 +;;; sequences for common combinatorial functions.
     1.6 +
     1.7 +;; by Mark Engelberg (mark.engelberg@gmail.com)
     1.8 +;; January 27, 2009
     1.9 +
    1.10 +(comment
    1.11 +"  
    1.12 +(combinations items n) - A lazy sequence of all the unique
    1.13 +ways of taking n different elements from items.
    1.14 +Example: (combinations [1 2 3] 2) -> ((1 2) (1 3) (2 3))
    1.15 +
    1.16 +(subsets items) - A lazy sequence of all the subsets of
    1.17 +items (but generalized to all sequences, not just sets).
    1.18 +Example: (subsets [1 2 3]) -> (() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3))
    1.19 +
    1.20 +(cartesian-product & seqs) - Takes any number of sequences
    1.21 +as arguments, and returns a lazy sequence of all the ways
    1.22 +to take one item from each seq.
    1.23 +Example: (cartesian-product [1 2] [3 4]) -> ((1 3) (1 4) (2 3) (2 4))
    1.24 +(cartesian-product seq1 seq2 seq3 ...) behaves like but is
    1.25 +faster than a nested for loop, such as:
    1.26 +(for [i1 seq1 i2 seq2 i3 seq3 ...] (list i1 i2 i3 ...))
    1.27 +
    1.28 +(selections items n) - A lazy sequence of all the ways to
    1.29 +take n (possibly the same) items from the sequence of items.
    1.30 +Example: (selections [1 2] 3) -> ((1 1 1) (1 1 2) (1 2 1) (1 2 2) (2 1 1) (2 1 2) (2 2 1) (2 2 2))
    1.31 +
    1.32 +(permutations items) - A lazy sequence of all the permutations
    1.33 +of items.
    1.34 +Example: (permutations [1 2 3]) -> ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
    1.35 +
    1.36 +(lex-permutations items) - A lazy sequence of all distinct
    1.37 +permutations in lexicographic order
    1.38 +(this function returns the permutations as
    1.39 +vectors).  Only works on sequences of comparable
    1.40 +items.  (Note that the result will be quite different from
    1.41 +permutations when the sequence contains duplicate items.)  
    1.42 +Example: (lex-permutations [1 1 2]) -> ([1 1 2] [1 2 1] [2 1 1])
    1.43 +
    1.44 +About permutations vs. lex-permutations:
    1.45 +lex-permutations is faster than permutations, but only works
    1.46 +on sequences of numbers.  They operate differently
    1.47 +on sequences with duplicate items (lex-permutations will only
    1.48 +give you back distinct permutations).  lex-permutations always
    1.49 +returns the permutations sorted lexicographically whereas
    1.50 +permutations will be in an order where the input sequence
    1.51 +comes first.  In general, I recommend using the regular
    1.52 +permutations function unless you have a specific
    1.53 +need for lex-permutations.
    1.54 +
    1.55 +About this code:
    1.56 +These combinatorial functions can be written in an elegant way using recursion.  However, when dealing with combinations and permutations, you're usually generating large numbers of things, and speed counts.  My objective was to write the fastest possible code I could, restricting myself to Clojure's functional, persistent data structures (rather than using Java's arrays) so that this code could be safely leveraged within Clojure's transactional concurrency system.
    1.57 +
    1.58 +I also restricted myself to algorithms that return results in a standard order.  For example, there are faster ways to generate cartesian-product, but I don't know of a faster way to generate the results in the standard nested-for-loop order.
    1.59 +
    1.60 +Most of these algorithms are derived from algorithms found in Knuth's wonderful Art of Computer Programming books (specifically, the volume 4 fascicles), which present fast, iterative solutions to these common combinatorial problems.  Unfortunately, these iterative versions are somewhat inscrutable.  If you want to better understand these algorithms, the Knuth books are the place to start.
    1.61 +
    1.62 +On my own computer, I use versions of all these algorithms that return sequences built with an uncached variation of lazy-seq.  Not only does this boost performance, but it's easier to use these rather large sequences more safely (from a memory consumption standpoint).  If some form of uncached sequences makes it into Clojure, I will update this accordingly.
    1.63 +"
    1.64 +)
    1.65 +
    1.66 +
    1.67 +(ns
    1.68 +  ^{:author "Mark Engelberg",
    1.69 +     :doc "Efficient, functional algorithms for generating lazy
    1.70 +sequences for common combinatorial functions. (See the source code 
    1.71 +for a longer description.)"}
    1.72 +  clojure.contrib.combinatorics)
    1.73 +
    1.74 +(defn- index-combinations
    1.75 +  [n cnt]
    1.76 +  (lazy-seq
    1.77 +   (let [c (vec (cons nil (for [j (range 1 (inc n))] (+ j cnt (- (inc n)))))),
    1.78 +	 iter-comb
    1.79 +	 (fn iter-comb [c j]
    1.80 +	   (if (> j n) nil
    1.81 +	       (let [c (assoc c j (dec (c j)))]
    1.82 +		 (if (< (c j) j) [c (inc j)]
    1.83 +		     (loop [c c, j j]
    1.84 +		       (if (= j 1) [c j]
    1.85 +			   (recur (assoc c (dec j) (dec (c j))) (dec j)))))))),
    1.86 +	 step
    1.87 +	 (fn step [c j]
    1.88 +	   (cons (rseq (subvec c 1 (inc n)))
    1.89 +		 (lazy-seq (let [next-step (iter-comb c j)]
    1.90 +			     (when next-step (step (next-step 0) (next-step 1)))))))]
    1.91 +     (step c 1))))
    1.92 +
    1.93 +(defn combinations
    1.94 +  "All the unique ways of taking n different elements from items"
    1.95 +  [items n]      
    1.96 +  (let [v-items (vec (reverse items))]
    1.97 +    (if (zero? n) (list ())
    1.98 +	(let [cnt (count items)]
    1.99 +	  (cond (> n cnt) nil
   1.100 +		(= n cnt) (list (seq items))
   1.101 +		:else
   1.102 +		(map #(map v-items %) (index-combinations n cnt)))))))
   1.103 +
   1.104 +(defn subsets
   1.105 +  "All the subsets of items"
   1.106 +  [items]
   1.107 +  (mapcat (fn [n] (combinations items n))
   1.108 +	  (range (inc (count items)))))
   1.109 +
   1.110 +(defn cartesian-product
   1.111 +  "All the ways to take one item from each sequence"
   1.112 +  [& seqs]
   1.113 +  (let [v-original-seqs (vec seqs)
   1.114 +	step
   1.115 +	(fn step [v-seqs]
   1.116 +	  (let [increment
   1.117 +		(fn [v-seqs]
   1.118 +		  (loop [i (dec (count v-seqs)), v-seqs v-seqs]
   1.119 +		    (if (= i -1) nil
   1.120 +			(if-let [rst (next (v-seqs i))]
   1.121 +			  (assoc v-seqs i rst)
   1.122 +			  (recur (dec i) (assoc v-seqs i (v-original-seqs i)))))))]
   1.123 +	    (when v-seqs
   1.124 +	       (cons (map first v-seqs)
   1.125 +		     (lazy-seq (step (increment v-seqs)))))))]
   1.126 +    (when (every? first seqs)
   1.127 +      (lazy-seq (step v-original-seqs)))))
   1.128 +
   1.129 +
   1.130 +(defn selections
   1.131 +  "All the ways of taking n (possibly the same) elements from the sequence of items"
   1.132 +  [items n]
   1.133 +  (apply cartesian-product (take n (repeat items))))
   1.134 +
   1.135 +
   1.136 +(defn- iter-perm [v]
   1.137 +  (let [len (count v),
   1.138 +	j (loop [i (- len 2)]
   1.139 +	     (cond (= i -1) nil
   1.140 +		   (< (v i) (v (inc i))) i
   1.141 +		   :else (recur (dec i))))]
   1.142 +    (when j
   1.143 +      (let [vj (v j),
   1.144 +	    l (loop [i (dec len)]
   1.145 +		(if (< vj (v i)) i (recur (dec i))))]
   1.146 +	(loop [v (assoc v j (v l) l vj), k (inc j), l (dec len)]
   1.147 +	  (if (< k l)
   1.148 +	    (recur (assoc v k (v l) l (v k)) (inc k) (dec l))
   1.149 +	    v))))))
   1.150 +
   1.151 +(defn- vec-lex-permutations [v]
   1.152 +  (when v (cons v (lazy-seq (vec-lex-permutations (iter-perm v))))))
   1.153 +
   1.154 +(defn lex-permutations
   1.155 +  "Fast lexicographic permutation generator for a sequence of numbers"
   1.156 +  [c]
   1.157 +  (lazy-seq
   1.158 +   (let [vec-sorted (vec (sort c))]
   1.159 +     (if (zero? (count vec-sorted))
   1.160 +       (list [])
   1.161 +       (vec-lex-permutations vec-sorted)))))
   1.162 +  
   1.163 +(defn permutations
   1.164 +  "All the permutations of items, lexicographic by index"
   1.165 +  [items]
   1.166 +  (let [v (vec items)]
   1.167 +    (map #(map v %) (lex-permutations (range (count v))))))