This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -0,0 +1,46 @@
(defun next-combination (n a)
(let ((k (length a)) m)
(loop for i from 1 do
(when (> i k) (return nil))
(when (< (aref a (- k i)) (- n i))
(setf m (aref a (- k i)))
(loop for j from i downto 1 do
(incf m)
(setf (aref a (- k j)) m))
(return t)))))
(defun all-combinations (n k)
(if (or (< k 0) (< n k)) '()
(let ((a (make-array k)))
(loop for i below k do (setf (aref a i) i))
(loop collect (coerce a 'list) while (next-combination n a)))))
(defun map-combinations (n k fun)
(if (and (>= k 0) (>= n k))
(let ((a (make-array k)))
(loop for i below k do (setf (aref a i) i))
(loop do (funcall fun (coerce a 'list)) while (next-combination n a)))))
; all-combinations returns a list of lists
> (all-combinations 4 3)
((0 1 2) (0 1 3) (0 2 3) (1 2 3))
; map-combinations applies a function to each combination
> (map-combinations 6 4 #'print)
(0 1 2 3)
(0 1 2 4)
(0 1 2 5)
(0 1 3 4)
(0 1 3 5)
(0 1 4 5)
(0 2 3 4)
(0 2 3 5)
(0 2 4 5)
(0 3 4 5)
(1 2 3 4)
(1 2 3 5)
(1 2 4 5)
(1 3 4 5)
(2 3 4 5)

View file

@ -0,0 +1 @@
.say for (^5).list.combinations(3).tree;

View file

@ -0,0 +1,10 @@
sub combinations(Int $n, Int $k) {
return [] if $k == 0;
return () if $k > $n;
gather {
take [0, (1..^$n)[@$_]] for combinations($n-1, $k-1);
take [(1..^$n)[@$_]] for combinations($n-1, $k );
}
}
.say for combinations(5, 3);

View file

@ -0,0 +1,8 @@
implicit def toComb(m: Int) = new AnyRef {
def comb(n: Int) = recurse(m, List.range(0, n))
private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match {
case (0, _) => List(Nil)
case (_, Nil) => Nil
case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail)
}
}

View file

@ -0,0 +1,2 @@
scala> (0 to 4 toList) combinations(3) toList
res1: List[List[Int]] = List(List(0, 1, 2), List(0, 1, 3), List(0, 1, 4), List(0, 2, 3), List(0, 2, 4), List(0, 3, 4), List(1, 2, 3), List(1, 2, 4), List(1, 3, 4), List(2, 3, 4))