Task

Given non-negative integers    m    and    n,   generate all size    m    combinations   of the integers from    0   (zero)   to    n-1    in sorted order   (each combination is sorted and the entire table is sorted).



Example

3   comb    5      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    1   (unity) instead of    0   (zero),

the combinations can be of the integers from    1   to    n. 



See also


 The number of samples of size k from n objects.


With   combinations and permutations   generation tasks. 






 Order Unimportant

 Order Important


 Without replacement








(


n
k


)




=

n



C

k


=



n
(
n
−
1
)
…
(
n
−
k
+
1
)


k
(
k
−
1
)
…
1





{\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}










n



P

k


=
n
⋅
(
n
−
1
)
⋅
(
n
−
2
)
⋯
(
n
−
k
+
1
)


{\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}




Task: Combinations

Task: Permutations


 With replacement








(



n
+
k
−
1

k


)




=

n
+
k
−
1



C

k


=



(
n
+
k
−
1
)
!


(
n
−
1
)
!
k
!





{\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}}








n

k




{\displaystyle n^{k}}




Task: Combinations with repetitions

Task: Permutations with repetitions



      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)
 