Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Combinations
note: Discrete math

View file

@ -0,0 +1,25 @@
;Task:
Given non-negative integers &nbsp; <big> '''m''' </big> &nbsp; and &nbsp; <big> '''n'''</big>, &nbsp; generate all size &nbsp; <big> '''m''' </big> &nbsp; [http://mathworld.wolfram.com/Combination.html combinations] &nbsp; of the integers from &nbsp; <big> '''0'''</big> &nbsp; (zero) &nbsp; to &nbsp; <big> '''n-1''' </big> &nbsp; in sorted order &nbsp; (each combination is sorted and the entire table is sorted).
;Example:
<big>'''3'''</big> &nbsp; comb &nbsp; <big> '''5''' </big> &nbsp; &nbsp; is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
If it is more "natural" in your language to start counting from &nbsp; <big> '''1'''</big> &nbsp; (unity) instead of &nbsp; <big> '''0'''</big> &nbsp; (zero),
<br>the combinations can be of the integers from &nbsp; <big> '''1'''</big> &nbsp; to &nbsp; <big> '''n'''. </big>
;See also:
{{Template:Combinations and permutations}}
<br><br>

View file

@ -0,0 +1,13 @@
F comb(arr, k)
I k == 0
R [[Int]()]
[[Int]] result
L(x) arr
V i = L.index
L(suffix) comb(arr[i+1..], k-1)
result [+]= x [+] suffix
R result
print(comb([0, 1, 2, 3, 4], 3))

View file

@ -0,0 +1,64 @@
* Combinations 26/05/2016
COMBINE CSECT
USING COMBINE,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
SR R3,R3 clear
LA R7,C @c(1)
LH R8,N v=n
LOOPI1 STC R8,0(R7) do i=1 to n; c(i)=n-i+1
LA R7,1(R7) @c(i)++
BCT R8,LOOPI1 next i
LOOPBIG LA R10,PG big loop {------------------
LH R1,N n
LA R7,C-1(R1) @c(i)
LH R6,N i=n
LOOPI2 IC R3,0(R7) do i=n to 1 by -1; r2=c(i)
XDECO R3,PG+80 edit c(i)
MVC 0(2,R10),PG+90 output c(i)
LA R10,3(R10) @pgi=@pgi+3
BCTR R7,0 @c(i)--
BCT R6,LOOPI2 next i
XPRNT PG,80 print buffer
LA R7,C @c(1)
LH R8,M v=m
LA R6,1 i=1
LOOPI3 LR R1,R6 do i=1 by 1; r1=i
IC R3,0(R7) c(i)
CR R3,R8 while c(i)>=m-i+1
BL ELOOPI3 leave i
CH R6,N if i>=n
BNL ELOOPBIG exit loop
BCTR R8,0 v=v-1
LA R7,1(R7) @c(i)++
LA R6,1(R6) i=i+1
B LOOPI3 next i
ELOOPI3 LR R1,R6 i
LA R4,C-1(R1) @c(i)
IC R3,0(R4) c(i)
LA R3,1(R3) c(i)+1
STC R3,0(R4) c(i)=c(i)+1
BCTR R7,0 @c(i)--
LOOPI4 CH R6,=H'2' do i=i to 2 by -1
BL ELOOPI4 leave i
IC R3,1(R7) c(i)
LA R3,1(R3) c(i)+1
STC R3,0(R7) c(i-1)=c(i)+1
BCTR R7,0 @c(i)--
BCTR R6,0 i=i-1
B LOOPI4 next i
ELOOPI4 B LOOPBIG big loop }------------------
ELOOPBIG L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
M DC H'5' <=input
N DC H'3' <=input
C DS 64X array of 8 bit integers
PG DC CL92' ' buffer
YREGS
END COMBINE

View file

@ -0,0 +1,32 @@
# -*- coding: utf-8 -*- #
COMMENT REQUIRED BY "prelude_combinations_generative.a68"
MODE COMBDATA = ~;
PROVIDES:
# COMBDATA*=~* #
# comb*=~ list* #
END COMMENT
MODE COMBDATALIST = REF[]COMBDATA;
MODE COMBDATALISTYIELD = PROC(COMBDATALIST)VOID;
PROC comb gen combinations = (INT m, COMBDATALIST list, COMBDATALISTYIELD yield)VOID:(
CASE m IN
# case 1: transpose list #
FOR i TO UPB list DO yield(list[i]) OD
OUT
[m + LWB list - 1]COMBDATA out;
INT index out := 1;
FOR i TO UPB list DO
COMBDATA first = list[i];
# FOR COMBDATALIST sub recombination IN # comb gen combinations(m - 1, list[i+1:] #) DO (#,
## (COMBDATALIST sub recombination)VOID:(
out[LWB list ] := first;
out[LWB list+1:] := sub recombination;
yield(out)
# OD #))
OD
ESAC
);
SKIP

View file

@ -0,0 +1,21 @@
#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
CO REQUIRED BY "prelude_combinations.a68" CO
MODE COMBDATA = INT;
#PROVIDES:#
# COMBDATA~=INT~ #
# comb ~=int list ~#
PR READ "prelude_combinations.a68" PR;
FORMAT data fmt = $g(0)$;
main:(
INT m = 3;
FORMAT list fmt = $"("n(m-1)(f(data fmt)",")f(data fmt)")"$;
FLEX[0]COMBDATA test data list := (1,2,3,4,5);
# FOR COMBDATALIST recombination data IN # comb gen combinations(m, test data list #) DO (#,
## (COMBDATALIST recombination)VOID:(
printf ((list fmt, recombination, $l$))
# OD # ))
)

View file

@ -0,0 +1,37 @@
BEGIN {
## Default values for r and n (Choose 3 from pool of 5). Can
## alternatively be set on the command line:-
## awk -v r=<number of items being chosen> -v n=<how many to choose from> -f <scriptname>
if (length(r) == 0) r = 3
if (length(n) == 0) n = 5
for (i=1; i <= r; i++) { ## First combination of items:
A[i] = i
if (i < r ) printf i OFS
else print i}
## While 1st item is less than its maximum permitted value...
while (A[1] < n - r + 1) {
## loop backwards through all items in the previous
## combination of items until an item is found that is
## less than its maximum permitted value:
for (i = r; i >= 1; i--) {
## If the equivalently positioned item in the
## previous combination of items is less than its
## maximum permitted value...
if (A[i] < n - r + i) {
## increment the current item by 1:
A[i]++
## Save the current position-index for use
## outside this "for" loop:
p = i
break}}
## Put consecutive numbers in the remainder of the array,
## counting up from position-index p.
for (i = p + 1; i <= r; i++) A[i] = A[i - 1] + 1
## Print the current combination of items:
for (i=1; i <= r; i++) {
if (i < r) printf A[i] OFS
else print A[i]}}
exit}

View file

@ -0,0 +1,70 @@
PROC PrintComb(BYTE ARRAY c BYTE len)
BYTE i
Put('()
FOR i=0 TO len-1
DO
IF i>0 THEN Put(',) FI
PrintB(c(i))
OD
Put(')) PutE()
RETURN
BYTE FUNC Increasing(BYTE ARRAY c BYTE len)
BYTE i
IF len<2 THEN RETURN (1) FI
FOR i=0 TO len-2
DO
IF c(i)>=c(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
BYTE FUNC NextComb(BYTE ARRAY c BYTE n,k)
INT pos,i
DO
pos=k-1
DO
c(pos)==+1
IF c(pos)<n THEN
EXIT
ELSE
pos==-1
IF pos<0 THEN RETURN (0) FI
FI
FOR i=pos+1 TO k-1
DO
c(i)=c(pos)
OD
OD
UNTIL Increasing(c,k)
OD
RETURN (1)
PROC Comb(BYTE n,k)
BYTE ARRAY c(10)
BYTE i
IF k>n THEN
Print("Error! k is greater than n.")
Break()
FI
FOR i=0 TO k-1
DO
c(i)=i
OD
DO
PrintComb(c,k)
UNTIL NextComb(c,n,k)=0
OD
RETURN
PROC Main()
Comb(5,3)
RETURN

View file

@ -0,0 +1,56 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Combinations is
generic
type Integers is range <>;
package Combinations is
type Combination is array (Positive range <>) of Integers;
procedure First (X : in out Combination);
procedure Next (X : in out Combination);
procedure Put (X : Combination);
end Combinations;
package body Combinations is
procedure First (X : in out Combination) is
begin
X (1) := Integers'First;
for I in 2..X'Last loop
X (I) := X (I - 1) + 1;
end loop;
end First;
procedure Next (X : in out Combination) is
begin
for I in reverse X'Range loop
if X (I) < Integers'Val (Integers'Pos (Integers'Last) - X'Last + I) then
X (I) := X (I) + 1;
for J in I + 1..X'Last loop
X (J) := X (J - 1) + 1;
end loop;
return;
end if;
end loop;
raise Constraint_Error;
end Next;
procedure Put (X : Combination) is
begin
for I in X'Range loop
Put (Integers'Image (X (I)));
end loop;
end Put;
end Combinations;
type Five is range 0..4;
package Fives is new Combinations (Five);
use Fives;
X : Combination (1..3);
begin
First (X);
loop
Put (X); New_Line;
Next (X);
end loop;
exception
when Constraint_Error =>
null;
end Test_Combinations;

View file

@ -0,0 +1 @@
type Five is range 0..4;

View file

@ -0,0 +1,27 @@
on comb(n, k)
set c to {}
repeat with i from 1 to k
set end of c to i's contents
end repeat
set r to {c's contents}
repeat while my next_comb(c, k, n)
set end of r to c's contents
end repeat
return r
end comb
on next_comb(c, k, n)
set i to k
set c's item i to (c's item i) + 1
repeat while (i > 1 and c's item i n - k + 1 + i)
set i to i - 1
set c's item i to (c's item i) + 1
end repeat
if (c's item 1 > n - k + 1) then return false
repeat with i from i + 1 to k
set c's item i to (c's item (i - 1)) + 1
end repeat
return true
end next_comb
return comb(5, 3)

View file

@ -0,0 +1 @@
{{1, 2, 3}, {1, 2, 4}, {1, 2, 5}, {1, 3, 4}, {1, 3, 5}, {1, 4, 5}, {2, 3, 4}, {2, 3, 5}, {2, 4, 5}, {3, 4, 5}}

View file

@ -0,0 +1,110 @@
----------------------- COMBINATIONS ---------------------
-- comb :: Int -> [a] -> [[a]]
on comb(n, lst)
if 1 > n then
{{}}
else
if not isNull(lst) then
set {h, xs} to uncons(lst)
map(cons(h), ¬
comb(n - 1, xs)) & comb(n, xs)
else
{}
end if
end if
end comb
--------------------------- TEST -------------------------
on run
intercalate(linefeed, ¬
map(unwords, comb(3, enumFromTo(0, 4))))
end run
-------------------- GENERIC FUNCTIONS -------------------
-- cons :: a -> [a] -> [a]
on cons(x)
script
on |λ|(xs)
{x} & xs
end |λ|
end script
end cons
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- isNull :: [a] -> Bool
on isNull(xs)
if class of xs is string then
xs = ""
else
xs = {}
end if
end isNull
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- uncons :: [a] -> Maybe (a, [a])
on uncons(xs)
set lng to length of xs
if lng > 0 then
if class of xs is string then
set cs to text items of xs
{item 1 of cs, rest of cs}
else
{item 1 of xs, rest of xs}
end if
else
missing value
end if
end uncons
-- unwords :: [String] -> String
on unwords(xs)
intercalate(space, xs)
end unwords

View file

@ -0,0 +1 @@
print.lines combine.by:3 @0..4

View file

@ -0,0 +1,26 @@
MsgBox % Comb(1,1)
MsgBox % Comb(3,3)
MsgBox % Comb(3,2)
MsgBox % Comb(2,3)
MsgBox % Comb(5,3)
Comb(n,t) { ; Generate all n choose t combinations of 1..n, lexicographically
IfLess n,%t%, Return
Loop %t%
c%A_Index% := A_Index
i := t+1, c%i% := n+1
Loop {
Loop %t%
i := t+1-A_Index, c .= c%i% " "
c .= "`n" ; combinations in new lines
j := 1, i := 2
Loop
If (c%j%+1 = c%i%)
c%j% := j, ++j, ++i
Else Break
If (j > t)
Return c
c%j% += 1
}
}

View file

@ -0,0 +1,13 @@
input "Enter n comb m. ", n
input m
outstr$ = ""
call iterate (outstr$, 0, m-1, n-1)
end
subroutine iterate (curr$, start, stp, depth)
for i = start to stp
if depth = 0 then print curr$ + " " + string(i)
call iterate (curr$ + " " + string(i), i+1, stp, depth-1)
next i
end subroutine

View file

@ -0,0 +1,45 @@
INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0,0)
M% = 3
N% = 5
C% = FNfact(N%)/(FNfact(M%)*FNfact(N%-M%))
DIM s$(C%)
PROCcomb(M%, N%, s$())
CALL sort%, s$(0)
FOR I% = 0 TO C%-1
PRINT s$(I%)
NEXT
END
DEF PROCcomb(C%, N%, s$())
LOCAL I%, U%
FOR U% = 0 TO 2^N%-1
IF FNbits(U%) = C% THEN
s$(I%) = FNlist(U%)
I% += 1
ENDIF
NEXT
ENDPROC
DEF FNbits(U%)
LOCAL N%
WHILE U%
N% += 1
U% = U% AND (U%-1)
ENDWHILE
= N%
DEF FNlist(U%)
LOCAL N%, s$
WHILE U%
IF U% AND 1 s$ += STR$(N%) + " "
N% += 1
U% = U% >> 1
ENDWHILE
= s$
DEF FNfact(N%)
IF N%<=1 THEN = 1 ELSE = N%*FNfact(N%-1)

View file

@ -0,0 +1,2 @@
Cmat{𝕨0𝕩?𝕨;0˘´1+(𝕨-10)𝕊¨𝕩-1} # Recursive
Cmat1{kd𝕩¬𝕨{k˘¨˜`1+𝕩}𝕨d100} # Roger Hui

View file

@ -0,0 +1,12 @@
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4

View file

@ -0,0 +1,24 @@
(comb=
bvar combination combinations list m n pat pvar var
. !arg:(?m.?n)
& ( pat
= ?
& !combinations (.!combination):?combinations
& ~
)
& :?list:?combination:?combinations
& whl
' ( !m+-1:~<0:?m
& chu$(utf$a+!m):?var
& glf$('(%@?.$var)):(=?pvar)
& '(? ()$pvar ()$pat):(=?pat)
& glf$('(!.$var)):(=?bvar)
& ( '$combination:(=)
& '$bvar:(=?combination)
| '($bvar ()$combination):(=?combination)
)
)
& whl
' (!n+-1:~<0:?n&!n !list:?list)
& !list:!pat
| !combinations);

View file

@ -0,0 +1,23 @@
#include <algorithm>
#include <iostream>
#include <string>
void comb(int N, int K)
{
std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's
// print integers and permute bitmask
do {
for (int i = 0; i < N; ++i) // [0..N-1] integers
{
if (bitmask[i]) std::cout << " " << i;
}
std::cout << std::endl;
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
int main()
{
comb(5, 3);
}

View file

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int[]> Combinations(int m, int n)
{
int[] result = new int[m];
Stack<int> stack = new Stack<int>();
stack.Push(0);
while (stack.Count > 0)
{
int index = stack.Count - 1;
int value = stack.Pop();
while (value < n)
{
result[index++] = ++value;
stack.Push(value);
if (index == m)
{
yield return result;
break;
}
}
}
}
static void Main()
{
foreach (int[] c in Combinations(3, 5))
{
Console.WriteLine(string.Join(",", c));
Console.WriteLine();
}
}
}

View file

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int[]> FindCombosRec(int[] buffer, int done, int begin, int end)
{
for (int i = begin; i < end; i++)
{
buffer[done] = i;
if (done == buffer.Length - 1)
yield return buffer;
else
foreach (int[] child in FindCombosRec(buffer, done+1, i+1, end))
yield return child;
}
}
public static IEnumerable<int[]> FindCombinations(int m, int n)
{
return FindCombosRec(new int[m], 0, 0, n);
}
static void Main()
{
foreach (int[] c in FindCombinations(3, 5))
{
for (int i = 0; i < c.Length; i++)
{
Console.Write(c[i] + " ");
}
Console.WriteLine();
}
}
}

View file

@ -0,0 +1,21 @@
using System;
class Combinations
{
static int k = 3, n = 5;
static int [] buf = new int [k];
static void Main()
{
rec(0, 0);
}
static void rec(int ind, int begin)
{
for (int i = begin; i < n; i++)
{
buf [ind] = i;
if (ind + 1 < k) rec(ind + 1, buf [ind] + 1);
else Console.WriteLine(string.Join(",", buf));
}
}
}

View file

@ -0,0 +1,29 @@
#include <stdio.h>
/* Type marker stick: using bits to indicate what's chosen. The stick can't
* handle more than 32 items, but the idea is there; at worst, use array instead */
typedef unsigned long marker;
marker one = 1;
void comb(int pool, int need, marker chosen, int at)
{
if (pool < need + at) return; /* not enough bits left */
if (!need) {
/* got all we needed; print the thing. if other actions are
* desired, we could have passed in a callback function. */
for (at = 0; at < pool; at++)
if (chosen & (one << at)) printf("%d ", at);
printf("\n");
return;
}
/* if we choose the current item, "or" (|) the bit to mark it so. */
comb(pool, need - 1, chosen | (one << at), at + 1);
comb(pool, need, chosen, at + 1); /* or don't choose it, go to next */
}
int main()
{
comb(5, 3, 0, 0);
return 0;
}

View file

@ -0,0 +1,27 @@
#include <stdio.h>
void comb(int m, int n, unsigned char *c)
{
int i;
for (i = 0; i < n; i++) c[i] = n - i;
while (1) {
for (i = n; i--;)
printf("%d%c", c[i], i ? ' ': '\n');
/* this check is not strictly necessary, but if m is not close to n,
it makes the whole thing quite a bit faster */
i = 0;
if (c[i]++ < m) continue;
for (; c[i] >= m - i;) if (++i >= n) return;
for (c[i]++; i; i--) c[i-1] = c[i] + 1;
}
}
int main()
{
unsigned char buf[100];
comb(5, 3, buf);
return 0;
}

View file

@ -0,0 +1,38 @@
% generate the size-M combinations from 0 to n-1
combinations = iter (m, n: int) yields (sequence[int])
if m<=n then
state: array[int] := array[int]$predict(1, m)
for i: int in int$from_to(0, m-1) do
array[int]$addh(state, i)
end
i: int := m
while i>0 do
yield (sequence[int]$a2s(state))
i := m
while i>0 do
state[i] := state[i] + 1
for j: int in int$from_to(i,m-1) do
state[j+1] := state[j] + 1
end
if state[i] < n-(m-i) then break end
i := i - 1
end
end
end
end combinations
% print a combination
print_comb = proc (s: stream, comb: sequence[int])
for i: int in sequence[int]$elements(comb) do
stream$puts(s, int$unparse(i) || " ")
end
end print_comb
start_up = proc ()
po: stream := stream$primary_output()
for comb: sequence[int] in combinations(3, 5) do
print_comb(po, comb)
stream$putl(po, "")
end
end start_up

View file

@ -0,0 +1,20 @@
(defn combinations
"If m=1, generate a nested list of numbers [0,n)
If m>1, for each x in [0,n), and for each list in the recursion on [x+1,n), cons the two"
[m n]
(letfn [(comb-aux
[m start]
(if (= 1 m)
(for [x (range start n)]
(list x))
(for [x (range start n)
xs (comb-aux (dec m) (inc x))]
(cons x xs))))]
(comb-aux m 0)))
(defn print-combinations
[m n]
(doseq [line (combinations m n)]
(doseq [n line]
(printf "%s " n))
(printf "%n")))

View file

@ -0,0 +1,11 @@
(defn combinations
"Generate the combinations of n elements from a list of [0..m)"
[m n]
(let [xs (range m)]
(loop [i (int 0) res #{#{}}]
(if (== i n)
res
(recur (+ 1 i)
(set (for [x xs r res
:when (not-any? #{x} r)]
(conj r x))))))))

View file

@ -0,0 +1,25 @@
combinations = (n, p) ->
return [ [] ] if p == 0
i = 0
combos = []
combo = []
while combo.length < p
if i < n
combo.push i
i += 1
else
break if combo.length == 0
i = combo.pop() + 1
if combo.length == p
combos.push clone combo
i = combo.pop() + 1
combos
clone = (arr) -> (n for n in arr)
N = 5
for i in [0..N]
console.log "------ #{N} #{i}"
for combo in combinations N, i
console.log combo

View file

@ -0,0 +1,18 @@
(defun map-combinations (m n fn)
"Call fn with each m combination of the integers from 0 to n-1 as a list. The list may be destroyed after fn returns."
(let ((combination (make-list m)))
(labels ((up-from (low)
(let ((start (1- low)))
(lambda () (incf start))))
(mc (curr left needed comb-tail)
(cond
((zerop needed)
(funcall fn combination))
((= left needed)
(map-into comb-tail (up-from curr))
(funcall fn combination))
(t
(setf (first comb-tail) curr)
(mc (1+ curr) (1- left) (1- needed) (rest comb-tail))
(mc (1+ curr) (1- left) needed comb-tail)))))
(mc 0 n m combination))))

View file

@ -0,0 +1,9 @@
(defun comb (m list fn)
(labels ((comb1 (l c m)
(when (>= (length l) m)
(if (zerop m) (return-from comb1 (funcall fn c)))
(comb1 (cdr l) c m)
(comb1 (cdr l) (cons (first l) c) (1- m)))))
(comb1 list nil m)))
(comb 3 '(0 1 2 3 4 5) #'print)

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,3 @@
def comb(m, n)
(0...n).to_a.each_combination(m) { |p| puts(p) }
end

View file

@ -0,0 +1,10 @@
[0, 1, 2]
[0, 1, 3]
[0, 1, 4]
[0, 2, 3]
[0, 2, 4]
[0, 3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]

View file

@ -0,0 +1,13 @@
T[][] comb(T)(in T[] arr, in int k) pure nothrow {
if (k == 0) return [[]];
typeof(return) result;
foreach (immutable i, immutable x; arr)
foreach (suffix; arr[i + 1 .. $].comb(k - 1))
result ~= x ~ suffix;
return result;
}
void main() {
import std.stdio;
[0, 1, 2, 3].comb(2).writeln;
}

View file

@ -0,0 +1,11 @@
import std.stdio, std.algorithm, std.range;
immutable(int)[][] comb(immutable int[] s, in int m) pure nothrow @safe {
if (!m) return [[]];
if (s.empty) return [];
return s[1 .. $].comb(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].comb(m);
}
void main() {
4.iota.array.comb(2).writeln;
}

View file

@ -0,0 +1,94 @@
module combinations3;
import std.traits: Unqual;
struct Combinations(T, bool copy=true) {
Unqual!T[] pool, front;
size_t r, n;
bool empty = false;
size_t[] indices;
size_t len;
bool lenComputed = false;
this(T[] pool_, in size_t r_) pure nothrow @safe {
this.pool = pool_.dup;
this.r = r_;
this.n = pool.length;
if (r > n)
empty = true;
indices.length = r;
foreach (immutable i, ref ini; indices)
ini = i;
front.length = r;
foreach (immutable i, immutable idx; indices)
front[i] = pool[idx];
}
@property size_t length() /*logic_const*/ pure nothrow @nogc {
static size_t binomial(size_t n, size_t k) pure nothrow @safe @nogc
in {
assert(n > 0, "binomial: n must be > 0.");
} body {
if (k < 0 || k > n)
return 0;
if (k > (n / 2))
k = n - k;
size_t result = 1;
foreach (size_t d; 1 .. k + 1) {
result *= n;
n--;
result /= d;
}
return result;
}
if (!lenComputed) {
// Set cache.
len = binomial(n, r);
lenComputed = true;
}
return len;
}
void popFront() pure nothrow @safe {
if (!empty) {
bool broken = false;
size_t pos = 0;
foreach_reverse (immutable i; 0 .. r) {
pos = i;
if (indices[i] != i + n - r) {
broken = true;
break;
}
}
if (!broken) {
empty = true;
return;
}
indices[pos]++;
foreach (immutable j; pos + 1 .. r)
indices[j] = indices[j - 1] + 1;
static if (copy)
front = new Unqual!T[front.length];
foreach (immutable i, immutable idx; indices)
front[i] = pool[idx];
}
}
}
Combinations!(T, copy) combinations(bool copy=true, T)
(T[] items, in size_t k)
in {
assert(items.length, "combinations: items can't be empty.");
} body {
return typeof(return)(items, k);
}
// Compile with -version=combinations3_main to run main.
version(combinations3_main)
void main() {
import std.stdio, std.array, std.algorithm;
[1, 2, 3, 4].combinations!false(2).array.writeln;
[1, 2, 3, 4].combinations!true(2).array.writeln;
[1, 2, 3, 4].combinations(2).map!(x => x).writeln;
}

View file

@ -0,0 +1,100 @@
module combinations4;
import std.stdio, std.algorithm, std.conv;
ulong choose(int n, int k) nothrow
in {
assert(n >= 0 && k >= 0, "choose: no negative input.");
} body {
static ulong[][] cache;
if (n < k)
return 0;
else if (n == k)
return 1;
while (n >= cache.length)
cache ~= [1UL]; // = choose(m, 0);
auto kmax = min(k, n - k);
while(kmax >= cache[n].length) {
immutable h = cache[n].length;
cache[n] ~= choose(n - 1, h - 1) + choose(n - 1, h);
}
return cache[n][kmax];
}
int largestV(in int p, in int q, in long r) nothrow
in {
assert(p > 0 && q >= 0 && r >= 0, "largestV: no negative input.");
} body {
auto v = p - 1;
while (choose(v, q) > r)
v--;
return v;
}
struct Comb {
immutable int n, m;
@property size_t length() const /*nothrow*/ {
return to!size_t(choose(n, m));
}
int[] opIndex(in size_t idx) const {
if (m < 0 || n < 0)
return [];
if (idx >= length)
throw new Exception("Out of bound");
ulong x = choose(n, m) - 1 - idx;
int a = n, b = m;
auto res = new int[m];
foreach (i; 0 .. m) {
a = largestV(a, b, x);
x = x - choose(a, b);
b = b - 1;
res[i] = n - 1 - a;
}
return res;
}
int opApply(int delegate(ref int[]) dg) const {
int[] yield;
foreach (i; 0 .. length) {
yield = this[i];
if (dg(yield))
break;
}
return 0;
}
static auto On(T)(in T[] arr, in int m) {
auto comb = Comb(arr.length, m);
return new class {
@property size_t length() const /*nothrow*/ {
return comb.length;
}
int opApply(int delegate(ref T[]) dg) const {
auto yield = new T[m];
foreach (c; comb) {
foreach (idx; 0 .. m)
yield[idx] = arr[c[idx]];
if (dg(yield))
break;
}
return 0;
}
};
}
}
version(combinations4_main)
void main() {
foreach (c; Comb.On([1, 2, 3], 2))
writeln(c);
}

View file

@ -0,0 +1,13 @@
def combinations(m, range) {
return if (m <=> 0) { [[]] } else {
def combGenerator {
to iterate(f) {
for i in range {
for suffix in combinations(m.previous(), range & (int > i)) {
f(null, [i] + suffix)
}
}
}
}
}
}

View file

@ -0,0 +1,36 @@
PROGRAM COMBINATIONS
CONST M_MAX=3,N_MAX=5
DIM COMBINATION[M_MAX],STACK[100,1]
PROCEDURE GENERATE(M)
LOCAL I
IF (M>M_MAX) THEN
FOR I=1 TO M_MAX DO
PRINT(COMBINATION[I];" ";)
END FOR
PRINT
ELSE
FOR N=1 TO N_MAX DO
IF ((M=1) OR (N>COMBINATION[M-1])) THEN
COMBINATION[M]=N
! --- PUSH STACK -----------
STACK[SP,0]=M STACK[SP,1]=N
SP=SP+1
! --------------------------
GENERATE(M+1)
! --- POP STACK ------------
SP=SP-1
M=STACK[SP,0] N=STACK[SP,1]
! --------------------------
END IF
END FOR
END IF
END PROCEDURE
BEGIN
GENERATE(1)
END PROGRAM

View file

@ -0,0 +1,15 @@
n = 5
m = 3
len result[] m
#
proc combinations pos val . .
if pos <= m
for i = val to n - m
result[pos] = pos + i
call combinations pos + 1 i
.
else
print result[]
.
.
call combinations 1 0

View file

@ -0,0 +1,25 @@
;;
;; using the native (combinations) function
(lib 'list)
(combinations (iota 5) 3)
→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))
;;
;; using an iterator
;;
(lib 'sequences)
(take (combinator (iota 5) 3) #:all)
→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))
;;
;; defining a function
;;
(define (combine lst p) (cond
[(null? lst) null]
[(< (length lst) p) null]
[(= (length lst) p) (list lst)]
[(= p 1) (map list lst)]
[else (append
(map cons (circular-list (first lst)) (combine (rest lst) (1- p)))
(combine (rest lst) p))]))
(combine (iota 5) 3)
→ ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4))

View file

@ -0,0 +1,6 @@
(define $comb
(lambda [$n $xs]
(match-all xs (list integer)
[(loop $i [1 ,n] <join _ <cons $a_i ...>> _) a])))
(test (comb 3 (between 0 4)))

View file

@ -0,0 +1,114 @@
class
COMBINATIONS
create
make
feature
make (n, k: INTEGER)
require
n_positive: n > 0
k_positive: k > 0
k_smaller_equal: k <= n
do
create set.make
set.extend ("")
create sol.make
sol := solve (set, k, n - k)
sol := convert_solution (n, sol)
ensure
correct_num_of_sol: num_of_comb (n, k) = sol.count
end
sol: LINKED_LIST [STRING]
feature {None}
set: LINKED_LIST [STRING]
convert_solution (n: INTEGER; solution: LINKED_LIST [STRING]): LINKED_LIST [STRING]
-- strings of 'k' digits between 1 and 'n'
local
i, j: INTEGER
temp: STRING
do
create temp.make (n)
from
i := 1
until
i > solution.count
loop
from
j := 1
until
j > n
loop
if solution [i].at (j) = '1' then
temp.append (j.out)
end
j := j + 1
end
solution [i].deep_copy (temp)
temp.wipe_out
i := i + 1
end
Result := solution
end
solve (seta: LINKED_LIST [STRING]; one, zero: INTEGER): LINKED_LIST [STRING]
-- list of strings with a number of 'one' 1s and 'zero' 0, standig for wether the corresponing digit is taken or not.
local
new_P1, new_P0: LINKED_LIST [STRING]
do
create new_P1.make
create new_P0.make
if one > 0 then
new_P1.deep_copy (seta)
across
new_P1 as P1
loop
new_P1.item.append ("1")
end
new_P1 := solve (new_P1, one - 1, zero)
end
if zero > 0 then
new_P0.deep_copy (seta)
across
new_P0 as P0
loop
new_P0.item.append ("0")
end
new_P0 := solve (new_P0, one, zero - 1)
end
if one = 0 and zero = 0 then
Result := seta
else
create Result.make
Result.fill (new_p0)
Result.fill (new_p1)
end
end
num_of_comb (n, k: INTEGER): INTEGER
-- number of 'k' sized combinations out of 'n'.
local
upper, lower, m, l: INTEGER
do
upper := 1
lower := 1
m := n
l := k
from
until
m < n - k + 1
loop
upper := m * upper
lower := l * lower
m := m - 1
l := l - 1
end
Result := upper // lower
end
end

View file

@ -0,0 +1,21 @@
class
APPLICATION
create
make
feature
make
do
create comb.make (5, 3)
across
comb.sol as ar
loop
io.put_string (ar.item.out + "%T")
end
end
comb: COMBINATIONS
end

View file

@ -0,0 +1,22 @@
import system'routines;
import extensions;
import extensions'routines;
const int M = 3;
const int N = 5;
Numbers(n)
{
^ Array.allocate(n).populate:(int n => n)
}
public program()
{
var numbers := Numbers(N);
Combinator.new(M, numbers).forEach:(row)
{
console.printLine(row.toString())
};
console.readChar()
}

View file

@ -0,0 +1,11 @@
defmodule RC do
def comb(0, _), do: [[]]
def comb(_, []), do: []
def comb(m, [h|t]) do
(for l <- comb(m-1, t), do: [h|l]) ++ comb(m, t)
end
end
{m, n} = {3, 5}
list = for i <- 1..n, do: i
Enum.each(RC.comb(m, list), fn x -> IO.inspect x end)

View file

@ -0,0 +1,11 @@
(defun comb-recurse (m n n-max)
(cond ((zerop m) '(()))
((= n-max n) '())
(t (append (mapcar #'(lambda (rest) (cons n rest))
(comb-recurse (1- m) (1+ n) n-max))
(comb-recurse m (1+ n) n-max)))))
(defun comb (m n)
(comb-recurse m 0 n))
(comb 3 5)

View file

@ -0,0 +1,9 @@
-module(comb).
-compile(export_all).
comb(0,_) ->
[[]];
comb(_,[]) ->
[];
comb(N,[H|T]) ->
[[H|L] || L <- comb(N-1,T)]++comb(N,T).

View file

@ -0,0 +1,13 @@
-module(comb).
-export([combinations/2]).
combinations(K, List) ->
lists:last(all_combinations(K, List)).
all_combinations(K, List) ->
lists:foldr(
fun(X, Next) ->
Sub = lists:sublist(Next, length(Next) - 1),
Step = [[]] ++ [[[X|S] || S <- L] || L <- Sub],
lists:zipwith(fun lists:append/2, Step, Next)
end, [[[]]] ++ lists:duplicate(K, []), List).

View file

@ -0,0 +1,22 @@
let choose m n =
let rec fC prefix m from = seq {
let rec loopFor f = seq {
match f with
| [] -> ()
| x::xs ->
yield (x, fC [] (m-1) xs)
yield! loopFor xs
}
if m = 0 then yield prefix
else
for (i, s) in loopFor from do
for x in s do
yield prefix@[i]@x
}
fC [] m [0..(n-1)]
[<EntryPoint>]
let main argv =
choose 3 5
|> Seq.iter (printfn "%A")
0

View file

@ -0,0 +1,3 @@
USING: math.combinatorics prettyprint ;
5 iota 3 all-combinations .

View file

@ -0,0 +1 @@
{ "a" "b" "c" } 2 all-combinations .

View file

@ -0,0 +1,89 @@
program Combinations
use iso_fortran_env
implicit none
type comb_result
integer, dimension(:), allocatable :: combs
end type comb_result
type(comb_result), dimension(:), pointer :: r
integer :: i, j
call comb(5, 3, r)
do i = 0, choose(5, 3) - 1
do j = 2, 0, -1
write(*, "(I4, ' ')", advance="no") r(i)%combs(j)
end do
deallocate(r(i)%combs)
write(*,*) ""
end do
deallocate(r)
contains
function choose(n, k, err)
integer :: choose
integer, intent(in) :: n, k
integer, optional, intent(out) :: err
integer :: imax, i, imin, ie
ie = 0
if ( (n < 0 ) .or. (k < 0 ) ) then
write(ERROR_UNIT, *) "negative in choose"
choose = 0
ie = 1
else
if ( n < k ) then
choose = 0
else if ( n == k ) then
choose = 1
else
imax = max(k, n-k)
imin = min(k, n-k)
choose = 1
do i = imax+1, n
choose = choose * i
end do
do i = 2, imin
choose = choose / i
end do
end if
end if
if ( present(err) ) err = ie
end function choose
subroutine comb(n, k, co)
integer, intent(in) :: n, k
type(comb_result), dimension(:), pointer, intent(out) :: co
integer :: i, j, s, ix, kx, hm, t
integer :: err
hm = choose(n, k, err)
if ( err /= 0 ) then
nullify(co)
return
end if
allocate(co(0:hm-1))
do i = 0, hm-1
allocate(co(i)%combs(0:k-1))
end do
do i = 0, hm-1
ix = i; kx = k
do s = 0, n-1
if ( kx == 0 ) exit
t = choose(n-(s+1), kx-1)
if ( ix < t ) then
co(i)%combs(kx-1) = s
kx = kx - 1
else
ix = ix - t
end if
end do
end do
end subroutine comb
end program Combinations

View file

@ -0,0 +1,32 @@
program combinations
implicit none
integer, parameter :: m_max = 3
integer, parameter :: n_max = 5
integer, dimension (m_max) :: comb
character (*), parameter :: fmt = '(i0' // repeat (', 1x, i0', m_max - 1) // ')'
call gen (1)
contains
recursive subroutine gen (m)
implicit none
integer, intent (in) :: m
integer :: n
if (m > m_max) then
write (*, fmt) comb
else
do n = 1, n_max
if ((m == 1) .or. (n > comb (m - 1))) then
comb (m) = n
call gen (m + 1)
end if
end do
end if
end subroutine gen
end program combinations

View file

@ -0,0 +1,16 @@
sub iterate( byval curr as string, byval start as uinteger,_
byval stp as uinteger, byval depth as uinteger )
dim as uinteger i
for i = start to stp
if depth = 0 then
print curr + " " + str(i)
end if
iterate( curr+" "+str(i), i+1, stp, depth-1 )
next i
return
end sub
dim as uinteger m, n
input "Enter n comb m. ", n, m
dim as string outstr = ""
iterate outstr, 0, m-1, n-1

View file

@ -0,0 +1,6 @@
# Built-in
Combinations([1 .. n], m);
Combinations([1 .. 5], 3);
# [ [ 1, 2, 3 ], [ 1, 2, 4 ], [ 1, 2, 5 ], [ 1, 3, 4 ], [ 1, 3, 5 ],
# [ 1, 4, 5 ], [ 2, 3, 4 ], [ 2, 3, 5 ], [ 2, 4, 5 ], [ 3, 4, 5 ] ]

View file

@ -0,0 +1,5 @@
5!3 >>> ,,\
$$(5!3) give all combinations of 3 out of 5
$$(>>>) sorted up,
$$(,,\) printed with crlf delimiters.

View file

@ -0,0 +1,11 @@
Result:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5

View file

@ -0,0 +1,29 @@
package main
import (
"fmt"
)
func main() {
comb(5, 3, func(c []int) {
fmt.Println(c)
})
}
func comb(n, m int, emit func([]int)) {
s := make([]int, m)
last := m - 1
var rc func(int, int)
rc = func(i, next int) {
for j := next; j < n; j++ {
s[i] = j
if i == last {
emit(s)
} else {
rc(i+1, j+1)
}
}
return
}
rc(0, 0)
}

View file

@ -0,0 +1,10 @@
def comb
comb = { m, list ->
def n = list.size()
m == 0 ?
[[]] :
(0..(n-m)).inject([]) { newlist, k ->
def sublist = (k+1 == n) ? [] : list[(k+1)..<n]
newlist += comb(m-1, sublist).collect { [list[k]] + it }
}
}

View file

@ -0,0 +1,3 @@
def csny = [ "Crosby", "Stills", "Nash", "Young" ]
println "Choose from ${csny}"
(0..(csny.size())).each { i -> println "Choose ${i}:"; comb(i, csny).each { println it }; println() }

View file

@ -0,0 +1 @@
def comb0 = { m, n -> comb(m, (0..<n)) }

View file

@ -0,0 +1,2 @@
println "Choose out of 5 (zero-based):"
(0..3).each { i -> println "Choose ${i}:"; comb0(i, 5).each { println it }; println() }

View file

@ -0,0 +1 @@
def comb1 = { m, n -> comb(m, (1..n)) }

View file

@ -0,0 +1,2 @@
println "Choose out of 5 (one-based):"
(0..3).each { i -> println "Choose ${i}:"; comb1(i, 5).each { println it }; println() }

View file

@ -0,0 +1,4 @@
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs

View file

@ -0,0 +1,5 @@
import Data.List (tails)
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb m l = [x:ys | x:xs <- tails l, ys <- comb (m-1) xs]

View file

@ -0,0 +1 @@
comb0 m n = comb m [0..n-1]

View file

@ -0,0 +1 @@
comb1 m n = comb m [1..n]

View file

@ -0,0 +1,2 @@
import Data.List (sort, subsequences)
comb m n = sort . filter ((==m) . length) $ subsequences [0..n-1]

View file

@ -0,0 +1 @@
comb m n = filter ((==m . length) $ filterM (const [True, False]) [0..n-1]

View file

@ -0,0 +1,12 @@
comb :: Int -> [a] -> [[a]]
comb m xs = combsBySize xs !! m
where
combsBySize = foldr f ([[]] : repeat [])
f x next =
zipWith
(<>)
(fmap (x :) <$> ([] : next))
next
main :: IO ()
main = print $ comb 3 [0 .. 4]

View file

@ -0,0 +1,20 @@
100 PROGRAM "Combinat.bas"
110 LET MMAX=3:LET NMAX=5
120 NUMERIC COMB(0 TO MMAX)
130 CALL GENERATE(1)
140 DEF GENERATE(M)
150 NUMERIC N,I
160 IF M>MMAX THEN
170 FOR I=1 TO MMAX
180 PRINT COMB(I);
190 NEXT
200 PRINT
220 ELSE
230 FOR N=0 TO NMAX-1
240 IF M=1 OR N>COMB(M-1) THEN
250 LET COMB(M)=N
260 CALL GENERATE(M+1)
270 END IF
280 NEXT
290 END IF
300 END DEF

View file

@ -0,0 +1,20 @@
procedure main()
return combinations(3,5,0)
end
procedure combinations(m,n,z) # demonstrate combinations
/z := 1
write(m," combinations of ",n," integers starting from ",z)
every put(L := [], z to n - 1 + z by 1) # generate list of n items from z
write("Intial list\n",list2string(L))
write("Combinations:")
every write(list2string(lcomb(L,m)))
end
procedure list2string(L) # helper function
every (s := "[") ||:= " " || (!L|"]")
return s
end
link lists

View file

@ -0,0 +1,8 @@
procedure lcomb(L,i) #: list combinations
local j
if i < 1 then fail
suspend if i = 1 then [!L]
else [L[j := 1 to *L - i + 1]] ||| lcomb(L[j + 1:0],i - 1)
end

View file

@ -0,0 +1 @@
require'stats'

View file

@ -0,0 +1,11 @@
3 comb 5
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4

View file

@ -0,0 +1,5 @@
comb1=: dyad define
c=. 1 {.~ - d=. 1+y-x
z=. i.1 0
for_j. (d-1+y)+/&i.d do. z=. (c#j) ,. z{~;(-c){.&.><i.{.c=. +/\.c end.
)

View file

@ -0,0 +1,10 @@
comb2=: dyad define
d =. 1 + y - x
k =. >: |. i. d
z =. < \. |. i. d
for. i.x-1 do.
z=. , each /\. k ,. each z
k =. 1 + k
end.
;{.z
)

View file

@ -0,0 +1,3 @@
combr=: dyad define M.
if. (x>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end.
)

View file

@ -0,0 +1,7 @@
combr=: dyad define
if.(x=#y) +. x=1 do.
y
else.
(({.y) ,. (x-1) combr (}.y)) , (x combr }.y)
end.
)

View file

@ -0,0 +1 @@
combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~)

View file

@ -0,0 +1,30 @@
import java.util.Collections;
import java.util.LinkedList;
public class Comb{
public static void main(String[] args){
System.out.println(comb(3,5));
}
public static String bitprint(int u){
String s= "";
for(int n= 0;u > 0;++n, u>>= 1)
if((u & 1) > 0) s+= n + " ";
return s;
}
public static int bitcount(int u){
int n;
for(n= 0;u > 0;++n, u&= (u - 1));//Turn the last set bit to a 0
return n;
}
public static LinkedList<String> comb(int c, int n){
LinkedList<String> s= new LinkedList<String>();
for(int u= 0;u < 1 << n;u++)
if(bitcount(u) == c) s.push(bitprint(u));
Collections.sort(s);
return s;
}
}

View file

@ -0,0 +1,18 @@
function bitprint(u) {
var s="";
for (var n=0; u; ++n, u>>=1)
if (u&1) s+=n+" ";
return s;
}
function bitcount(u) {
for (var n=0; u; ++n, u=u&(u-1));
return n;
}
function comb(c,n) {
var s=[];
for (var u=0; u<1<<n; u++)
if (bitcount(u)==c)
s.push(bitprint(u))
return s.sort();
}
comb(3,5)

View file

@ -0,0 +1,25 @@
function combinations(arr, k){
var i,
subI,
ret = [],
sub,
next;
for(i = 0; i < arr.length; i++){
if(k === 1){
ret.push( [ arr[i] ] );
}else{
sub = combinations(arr.slice(i+1, arr.length), k-1);
for(subI = 0; subI < sub.length; subI++ ){
next = sub[subI];
next.unshift(arr[i]);
ret.push( next );
}
}
}
return ret;
}
combinations([0,1,2,3,4], 3);
// produces: [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
combinations(["Crosby", "Stills", "Nash", "Young"], 3);
// produces: [["Crosby", "Stills", "Nash"], ["Crosby", "Stills", "Young"], ["Crosby", "Nash", "Young"], ["Stills", "Nash", "Young"]]

View file

@ -0,0 +1,29 @@
(function () {
function comb(n, lst) {
if (!n) return [[]];
if (!lst.length) return [];
var x = lst[0],
xs = lst.slice(1);
return comb(n - 1, xs).map(function (t) {
return [x].concat(t);
}).concat(comb(n, xs));
}
// [m..n]
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
return comb(3, range(0, 4))
.map(function (x) {
return x.join(' ');
}).join('\n');
})();

View file

@ -0,0 +1,46 @@
(function (n) {
// n -> [a] -> [[a]]
function comb(n, lst) {
if (!n) return [[]];
if (!lst.length) return [];
var x = lst[0],
xs = lst.slice(1);
return comb(n - 1, xs).map(function (t) {
return [x].concat(t);
}).concat(comb(n, xs));
}
// f -> f
function memoized(fn) {
m = {};
return function (x) {
var args = [].slice.call(arguments),
strKey = args.join('-');
v = m[strKey];
if ('u' === (typeof v)[0])
m[strKey] = v = fn.apply(null, args);
return v;
}
}
// [m..n]
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
var fnMemoized = memoized(comb),
lstRange = range(0, 4);
return fnMemoized(n, lstRange)
.map(function (x) {
return x.join(' ');
}).join('\n');
})(3);

View file

@ -0,0 +1,10 @@
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4

View file

@ -0,0 +1,61 @@
(() => {
'use strict';
// ------------------ COMBINATIONS -------------------
// combinations :: Int -> [a] -> [[a]]
const combinations = n =>
xs => {
const comb = n => xs => {
return 1 > n ? [
[]
] : 0 === xs.length ? (
[]
) : (() => {
const
h = xs[0],
tail = xs.slice(1);
return comb(n - 1)(tail)
.map(cons(h))
.concat(comb(n)(tail));
})()
};
return comb(n)(xs);
};
// ---------------------- TEST -----------------------
const main = () =>
show(
combinations(3)(
enumFromTo(0)(4)
)
);
// ---------------- GENERIC FUNCTIONS ----------------
// cons :: a -> [a] -> [a]
const cons = x =>
// A list constructed from the item x,
// followed by the existing list xs.
xs => [x].concat(xs);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => !isNaN(m) ? (
Array.from({
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
// show :: a -> String
const show = (...x) =>
JSON.stringify.apply(
null, x.length > 1 ? [x[0], null, x[1]] : x
);
// MAIN ---
return main();
})();

View file

@ -0,0 +1,91 @@
(() => {
'use strict';
// ------------------ COMBINATIONS -------------------
// comb :: Int -> Int -> [[Int]]
const comb = m =>
n => combinations(m)(
enumFromTo(0)(n - 1)
);
// combinations :: Int -> [a] -> [[a]]
const combinations = k =>
xs => sort(
filter(xs => k === xs.length)(
subsequences(xs)
)
);
// --------------------- TEST ---------------------
const main = () =>
show(
comb(3)(5)
);
// ---------------- GENERIC FUNCTIONS ----------------
// cons :: a -> [a] -> [a]
const cons = x =>
// A list constructed from the item x,
// followed by the existing list xs.
xs => [x].concat(xs);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => !isNaN(m) ? (
Array.from({
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = p =>
// The elements of xs which match
// the predicate p.
xs => [...xs].filter(p);
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs || []);
// show :: a -> String
const show = x =>
// JSON stringification of a JS value.
JSON.stringify(x)
// sort :: Ord a => [a] -> [a]
const sort = xs => list(xs).slice()
.sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));
// subsequences :: [a] -> [[a]]
// subsequences :: String -> [String]
const subsequences = xs => {
const
// nonEmptySubsequences :: [a] -> [[a]]
nonEmptySubsequences = xxs => {
if (xxs.length < 1) return [];
const [x, xs] = [xxs[0], xxs.slice(1)];
const f = (r, ys) => cons(ys)(cons(cons(x)(ys))(r));
return cons([x])(nonEmptySubsequences(xs)
.reduceRight(f, []));
};
return ('string' === typeof xs) ? (
cons('')(nonEmptySubsequences(xs.split(''))
.map(x => ''.concat.apply('', x)))
) : cons([])(nonEmptySubsequences(xs));
};
// MAIN ---
return main();
})();

View file

@ -0,0 +1,7 @@
function combinations(k, arr, prefix = []) {
if (prefix.length == 0) arr = [...Array(arr).keys()];
if (k == 0) return [prefix];
return arr.flatMap((v, i) =>
combinations(k - 1, arr.slice(i + 1), [...prefix, v])
);
}

View file

@ -0,0 +1,9 @@
def combination(r):
if r > length or r < 0 then empty
elif r == length then .
else ( [.[0]] + (.[1:]|combination(r-1))),
( .[1:]|combination(r))
end;
# select r integers from the set (0 .. n-1)
def combinations(n;r): [range(0;n)] | combination(r);

View file

@ -0,0 +1,6 @@
using Combinatorics
n = 4
m = 3
for i in combinations(0:n,m)
println(i')
end

View file

@ -0,0 +1,27 @@
##############################
# COMBINATIONS OF 3 OUT OF 5 #
##############################
# Set n and m
m = 5
n = 3
# Prepare the boundary of the calculation. Only m - n numbers are changing in each position.
max_n = m - n
#Prepare an array for result
result = zeros(Int64, n)
function combinations(pos, val) # n, max_n and result are visible in the function
for i = val:max_n # from current value to the boundary
result[pos] = pos + i # fill the position of result
if pos < n # if combination isn't complete,
combinations(pos+1, i) # go to the next position
else
println(result) # combination is complete, print it
end
end
end
combinations(1, 0)
end

View file

@ -0,0 +1,20 @@
using Base.Iterators
function bitmask(u, max_size)
res = BitArray(undef, max_size)
res.chunks[1] = u%UInt64
res
end
function combinations(input_collection::Vector{T}, choice_size::Int)::Vector{Vector{T}} where T
num_elements = length(input_collection)
size_filter(x) = Iterators.filter(y -> count_ones(y) == choice_size, x)
bitmask_map(x) = Iterators.map(y -> bitmask(y, num_elements), x)
getindex_map(x) = Iterators.map(y -> input_collection[y], x)
UnitRange(0, (2^num_elements)-1) |>
size_filter |>
bitmask_map |>
getindex_map |>
collect
end

View file

@ -0,0 +1,4 @@
comb:{[n;k]
f:{:[k=#x; :,x; :,/_f' x,'(1+*|x) _ !n]}
:,/f' !n
}

View file

@ -0,0 +1,25 @@
class Combinations(val m: Int, val n: Int) {
private val combination = IntArray(m)
init {
generate(0)
}
private fun generate(k: Int) {
if (k >= m) {
for (i in 0 until m) print("${combination[i]} ")
println()
}
else {
for (j in 0 until n)
if (k == 0 || j > combination[k - 1]) {
combination[k] = j
generate(k + 1)
}
}
}
}
fun main(args: Array<String>) {
Combinations(3, 5)
}

View file

@ -0,0 +1,28 @@
import java.util.LinkedList
inline fun <reified T> combinations(arr: Array<T>, m: Int) = sequence {
val n = arr.size
val result = Array(m) { arr[0] }
val stack = LinkedList<Int>()
stack.push(0)
while (stack.isNotEmpty()) {
var resIndex = stack.size - 1;
var arrIndex = stack.pop()
while (arrIndex < n) {
result[resIndex++] = arr[arrIndex++]
stack.push(arrIndex)
if (resIndex == m) {
yield(result.toList())
break
}
}
}
}
fun main() {
val n = 5
val m = 3
combinations((1..n).toList().toTypedArray(), m).forEach { println(it.joinToString(separator = " ")) }
}

Some files were not shown because too many files have changed in this diff Show more