Combinations: Difference between revisions

m
no edit summary
m (→‎{{header|Picat}}: Bad end tag)
imported>Lacika7
mNo edit summary
 
(20 intermediate revisions by 14 users not shown)
Line 28:
=={{header|11l}}==
{{trans|D}}
<langsyntaxhighlight lang="11l">F comb(arr, k)
I k == 0
R [[Int]()]
Line 40:
R result
 
print(comb([0, 1, 2, 3, 4], 3))</langsyntaxhighlight>
{{out}}
<pre>
Line 52:
For maximum compatibility, this program uses only the basic instruction set (S/360)
and two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Combinations 26/05/2016
COMBINE CSECT
USING COMBINE,R13 base register
Line 115:
PG DC CL92' ' buffer
YREGS
END COMBINE</langsyntaxhighlight>
{{out}}
<pre>
Line 128:
2 4 5
3 4 5
</pre>
 
=={{header|Acornsoft Lisp}}==
{{trans|Emacs Lisp}}
 
<syntaxhighlight lang="lisp">
(defun comb (m n (i . 0))
(cond ((zerop m) '(()))
((eq i n) '())
(t (append
(mapc '(lambda (rest) (cons i rest))
(comb (sub1 m) n (add1 i)))
(comb m n (add1 i))))))
 
(defun append (a b)
(cond ((null a) b)
(t (cons (car a) (append (cdr a) b)))))
 
(map print (comb 3 5))
</syntaxhighlight>
 
{{Out}}
 
<pre>
(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)
</pre>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintComb(BYTE ARRAY c BYTE len)
BYTE i
 
Line 200 ⟶ 234:
PROC Main()
Comb(5,3)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Combinations.png Screenshot from Atari 8-bit computer]
Line 217 ⟶ 251:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Combinations is
Line 272 ⟶ 306:
when Constraint_Error =>
null;
end Test_Combinations;</langsyntaxhighlight>
The solution is generic the formal parameter is the integer type to make combinations of. The type range determines ''n''.
In the example it is
<langsyntaxhighlight lang="ada">type Five is range 0..4;</langsyntaxhighlight>
The parameter ''m'' is the object's constraint.
When ''n'' < ''m'' the procedure First (selects the first combination) will propagate Constraint_Error.
Line 299 ⟶ 333:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude_combinations.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
COMMENT REQUIRED BY "prelude_combinations_generative.a68"
Line 330 ⟶ 364:
);
 
SKIP</langsyntaxhighlight>'''File: test_combinations.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 351 ⟶ 385:
# OD # ))
)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 370 ⟶ 404:
===Iteration===
 
<langsyntaxhighlight AppleScriptlang="applescript">on comb(n, k)
set c to {}
repeat with i from 1 to k
Line 396 ⟶ 430:
end next_comb
 
return comb(5, 3)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{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}}</langsyntaxhighlight>
 
===Functional composition===
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">----------------------- COMBINATIONS ---------------------
 
-- comb :: Int -> [a] -> [[a]]
Line 511 ⟶ 545:
on unwords(xs)
intercalate(space, xs)
end unwords</langsyntaxhighlight>
{{Out}}
<pre>0 1 2
Line 523 ⟶ 557:
1 3 4
2 3 4</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">print.lines combine.by:3 @0..4</syntaxhighlight>
 
{{out}}
 
<pre>[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]</pre>
 
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276224.html#276224 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % Comb(1,1)
MsgBox % Comb(3,3)
MsgBox % Comb(3,2)
Line 551 ⟶ 601:
c%j% += 1
}
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
## Default values for r and n (Choose 3 from pool of 5). Can
## alternatively be set on the command line:-
Line 590 ⟶ 640:
if (i < r) printf A[i] OFS
else print A[i]}}
exit}</langsyntaxhighlight>
 
Usage:
Line 610 ⟶ 660:
3 4 5
</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">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</syntaxhighlight>
{{out}}
<pre>Enter n comb m. 3
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</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">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</syntaxhighlight>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">SUB iterate (curr$, start, stp, depth)
FOR i = start TO stp
IF depth = 0 THEN PRINT curr$ + " " + STR$(i)
CALL iterate(curr$ + " " + STR$(i), i + 1, stp, depth - 1)
NEXT i
END SUB
 
INPUT "Enter n comb m. ", n, m
 
outstr$ = ""
CALL iterate(outstr$, 0, m - 1, n - 1)
END</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="vb">sub iterate curr$, start, stp, depth
for i = start to stp
if depth = 0 then print curr$ + " " + str$(i)
call iterate curr$ + " " + str$(i), i+1, stp, depth-1
next i
end sub
 
input "Enter n comb m. "; n, m
outstr$ = ""
call iterate outstr$, 0, m-1, n-1
end</syntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Combinations"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
DECLARE FUNCTION iterate (curr$, start, stp, depth)
 
FUNCTION Entry ()
n = 3
m = 5
outstr$ = ""
iterate(outstr$, 0, m - 1, n - 1)
 
END FUNCTION
 
FUNCTION iterate (curr$, start, stp, depth)
FOR i = start TO stp
IF depth = 0 THEN PRINT curr$ + " " + STR$(i)
iterate(curr$ + " " + STR$(i), i + 1, stp, depth - 1)
NEXT i
RETURN
END FUNCTION
END PROGRAM</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
sort% = FN_sortinit(0,0)
Line 658 ⟶ 815:
DEF FNfact(N%)
IF N%<=1 THEN = 1 ELSE = N%*FNfact(N%-1)
</syntaxhighlight>
</lang>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Cmat←{⊑𝕨∊0‿𝕩?≍↕𝕨;0⊸∾˘⊸∾´1+(𝕨-1‿0)𝕊¨𝕩-1} # Recursive
Cmat1←{k←⌽↕d←𝕩¬𝕨⋄∾⌽{k∾˘¨∾˜`1+𝕩}⍟𝕨d↑↓1‿0⥊0} # Roger Hui</syntaxhighlight>
<syntaxhighlight lang="text">┌─
╵ 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
┘</syntaxhighlight>
=={{header|Bracmat}}==
The program first constructs a pattern with <code>m</code> variables and an expression that evaluates <code>m</code> variables into a combination.
Line 666 ⟶ 838:
When all combinations are found, the pattern fails and we are in the rhs of the last <code>|</code> operator.
 
<langsyntaxhighlight lang="bracmat">(comb=
bvar combination combinations list m n pat pvar var
. !arg:(?m.?n)
Line 689 ⟶ 861:
' (!n+-1:~<0:?n&!n !list:?list)
& !list:!pat
| !combinations);</langsyntaxhighlight>
comb$(3.5)
Line 705 ⟶ 877:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
/* Type marker stick: using bits to indicate what's chosen. The stick can't
Line 733 ⟶ 905:
comb(5, 3, 0, 0);
return 0;
}</langsyntaxhighlight>
 
===Lexicographic ordered generation===
Without recursions, generate all combinations in sequence. Basic logic: put n items in the first n of m slots; each step, if right most slot can be moved one slot further right, do so; otherwise
find right most item that can be moved, move it one step and put all items already to its right next to it.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void comb(int m, int n, unsigned char *c)
Line 764 ⟶ 936:
comb(5, 3, buf);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 805 ⟶ 977:
}
}
}</langsyntaxhighlight>
 
Here is another implementation that uses recursion, intead of an explicit stack:
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 846 ⟶ 1,018:
}
}
</syntaxhighlight>
</lang>
 
 
Line 852 ⟶ 1,024:
 
Recursive version
<langsyntaxhighlight lang="csharp">using System;
class Combinations
{
Line 872 ⟶ 1,044:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <string>
Line 897 ⟶ 1,069:
{
comb(5, 3);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 913 ⟶ 1,085:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(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"
Line 932 ⟶ 1,104:
(doseq [n line]
(printf "%s " n))
(printf "%n")))</langsyntaxhighlight>
 
The below code do not comply to the task described above. However, the combinations of n elements taken from m elements might be more natural to be expressed as a set of unordered sets of elements in Clojure using its Set data structure.
 
<langsyntaxhighlight lang="clojure">
(defn combinations
"Generate the combinations of n elements from a list of [0..m)"
Line 948 ⟶ 1,120:
:when (not-any? #{x} r)]
(conj r x))))))))
</syntaxhighlight>
</lang>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% generate the size-M combinations from 0 to n-1
combinations = iter (m, n: int) yields (sequence[int])
if m<=n then
Line 988 ⟶ 1,160:
stream$putl(po, "")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>0 1 2
Line 1,003 ⟶ 1,175:
=={{header|CoffeeScript}}==
Basic backtracking solution.
<langsyntaxhighlight lang="coffeescript">
combinations = (n, p) ->
return [ [] ] if p == 0
Line 1,030 ⟶ 1,202:
console.log combo
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,076 ⟶ 1,248:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(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)))
Line 1,093 ⟶ 1,265:
(mc (1+ curr) (1- left) (1- needed) (rest comb-tail))
(mc (1+ curr) (1- left) needed comb-tail)))))
(mc 0 n m combination))))</langsyntaxhighlight>
 
{{out}}Example use
Line 1,111 ⟶ 1,283:
 
=== Recursive method ===
<langsyntaxhighlight lang="lisp">(defun comb (m list fn)
(labels ((comb1 (l c m)
(when (>= (length l) m)
Line 1,119 ⟶ 1,291:
(comb1 list nil m)))
 
(comb 3 '(0 1 2 3 4 5) #'print)</langsyntaxhighlight>
 
=== Alternate, iterative method ===
<langsyntaxhighlight lang="lisp">(defun next-combination (n a)
(let ((k (length a)) m)
(loop for i from 1 do
Line 1,167 ⟶ 1,339:
(1 2 4 5)
(1 3 4 5)
(2 3 4 5)</langsyntaxhighlight>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
def comb(m, n)
(0...n).to_a.each_combination(m) { |p| puts(p) }
end
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="bash">
<lang Bash>
[0, 1, 2]
[0, 1, 3]
Line 1,187 ⟶ 1,359:
[1, 3, 4]
[2, 3, 4]
</syntaxhighlight>
</lang>
 
=={{header|D}}==
===Slow Recursive Version===
{{trans|Python}}
<langsyntaxhighlight lang="d">T[][] comb(T)(in T[] arr, in int k) pure nothrow {
if (k == 0) return [[]];
typeof(return) result;
Line 1,204 ⟶ 1,376:
import std.stdio;
[0, 1, 2, 3].comb(2).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]</pre>
Line 1,211 ⟶ 1,383:
{{trans|Haskell}}
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
immutable(int)[][] comb(immutable int[] s, in int m) pure nothrow @safe {
Line 1,221 ⟶ 1,393:
void main() {
4.iota.array.comb(2).writeln;
}</langsyntaxhighlight>
 
===Lazy Version===
<langsyntaxhighlight lang="d">module combinations3;
 
import std.traits: Unqual;
Line 1,317 ⟶ 1,489:
[1, 2, 3, 4].combinations!true(2).array.writeln;
[1, 2, 3, 4].combinations(2).map!(x => x).writeln;
}</langsyntaxhighlight>
 
===Lazy Lexicographical Combinations===
Includes an algorithm to find [http://msdn.microsoft.com/en-us/library/aa289166.aspx#mth_lexicograp_topic3 mth Lexicographical Element of a Combination].
<langsyntaxhighlight lang="d">module combinations4;
import std.stdio, std.algorithm, std.conv;
 
Line 1,420 ⟶ 1,592:
foreach (c; Comb.On([1, 2, 3], 2))
writeln(c);
}</langsyntaxhighlight>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Combinations#Pascal Pascal].
=={{header|E}}==
<langsyntaxhighlight lang="e">def combinations(m, range) {
return if (m <=> 0) { [[]] } else {
def combGenerator {
Line 1,436 ⟶ 1,608:
}
}
}</langsyntaxhighlight>
 
? for x in combinations(3, 0..4) { println(x) }
Line 1,442 ⟶ 1,614:
=={{header|EasyLang}}==
{{trans|Julia}}
<syntaxhighlight lang="text">
<lang>n = 5
n = 5
m = 3
len result[] m
#
funcproc 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 01 0</lang>
</syntaxhighlight>
{{out}}
<pre>
[ 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 2 5 ]
[ 1 3 4 ]
[ 1 3 5 ]
[ 1 4 5 ]
[ 2 3 4 ]
[ 2 3 5 ]
[ 2 4 5 ]
[ 3 4 5 ]
</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;;
;; using the native (combinations) function
Line 1,498 ⟶ 1,672:
(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))
</syntaxhighlight>
</lang>
 
=={{header|Egison}}==
 
<langsyntaxhighlight lang="egison">
(define $comb
(lambda [$n $xs]
Line 1,509 ⟶ 1,683:
 
(test (comb 3 (between 0 4)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,517 ⟶ 1,691:
=={{header|Eiffel}}==
The core of the program is the recursive feature solve, which returns all possible strings of length n with k "ones" and n-k "zeros". The strings are then evaluated, each resulting in k corresponding integers for the digits where ones are found.
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 1,633 ⟶ 1,807:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,658 ⟶ 1,832:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,665 ⟶ 1,839:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions'routines;
Line 1,675 ⟶ 1,849:
Numbers(n)
{
^ Array.allocate(n).populate::(int n => n)
}
 
Line 1,681 ⟶ 1,855:
{
var numbers := Numbers(N);
Combinator.new(M, numbers).forEach::(row)
{
console.printLine(row.toString())
Line 1,687 ⟶ 1,861:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,704 ⟶ 1,878:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def comb(0, _), do: [[]]
def comb(_, []), do: []
Line 1,714 ⟶ 1,888:
{m, n} = {3, 5}
list = for i <- 1..n, do: i
Enum.each(RC.comb(m, list), fn x -> IO.inspect x end)</langsyntaxhighlight>
 
{{out}}
Line 1,732 ⟶ 1,906:
=={{header|Emacs Lisp}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="lisp">(defun comb-recurse (m n n-max)
(cond ((zerop m) '(()))
((= n-max n) '())
Line 1,742 ⟶ 1,916:
(comb-recurse m 0 n))
 
(comb 3 5)</langsyntaxhighlight>
 
{{out}}
Line 1,749 ⟶ 1,923:
=={{header|Erlang}}==
 
<langsyntaxhighlight lang="erlang">
-module(comb).
-compile(export_all).
Line 1,759 ⟶ 1,933:
comb(N,[H|T]) ->
[[H|L] || L <- comb(N-1,T)]++comb(N,T).
</syntaxhighlight>
</lang>
 
===Dynamic Programming===
Line 1,767 ⟶ 1,941:
Could be optimized with a custom <code>zipwith/3</code> function instead of using <code>lists:sublist/2</code>.
 
<langsyntaxhighlight lang="erlang">
-module(comb).
-export([combinations/2]).
Line 1,781 ⟶ 1,955:
lists:zipwith(fun lists:append/2, Step, Next)
end, [[[]]] ++ lists:duplicate(K, []), List).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM COMBINATIONS
 
Line 1,821 ⟶ 1,995:
GENERATE(1)
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,837 ⟶ 2,011:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let choose m n =
let rec fC prefix m from = seq {
let rec loopFor f = seq {
Line 1,858 ⟶ 2,032:
choose 3 5
|> Seq.iter (printfn "%A")
0</langsyntaxhighlight>
{{out}}
<pre>[0; 1; 2]
Line 1,872 ⟶ 2,046:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: math.combinatorics prettyprint ;
 
5 iota 3 all-combinations .</langsyntaxhighlight>
<pre>
{
Line 1,890 ⟶ 2,064:
</pre>
This works with any kind of sequence:
<langsyntaxhighlight lang="factor">{ "a" "b" "c" } 2 all-combinations .</langsyntaxhighlight>
<pre>{ { "a" "b" } { "a" "c" } { "b" "c" } }</pre>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program Combinations
use iso_fortran_env
implicit none
Line 1,982 ⟶ 2,156:
end subroutine comb
 
end program Combinations</langsyntaxhighlight>
Alternatively:
<langsyntaxhighlight lang="fortran">program combinations
 
implicit none
Line 2,015 ⟶ 2,189:
end subroutine gen
 
end program combinations</langsyntaxhighlight>
{{out}}
<pre>1 2 3
Line 2,031 ⟶ 2,205:
This is remarkably compact and elegant.
 
<langsyntaxhighlight lang="freebasic">sub iterate( byval curr as string, byval start as uinteger,_
byval stp as uinteger, byval depth as uinteger )
dim as uinteger i
Line 2,046 ⟶ 2,220:
input "Enter n comb m. ", n, m
dim as string outstr = ""
iterate outstr, 0, m-1, n-1</langsyntaxhighlight>
{{out}}
<pre>Enter n comb m. 3,5
Line 2,061 ⟶ 2,235:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># 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 ] ]</langsyntaxhighlight>
 
=={{header|Glee}}==
<langsyntaxhighlight lang="glee">5!3 >>> ,,\
 
$$(5!3) give all combinations of 3 out of 5
$$(>>>) sorted up,
$$(,,\) printed with crlf delimiters.</langsyntaxhighlight>
 
Result:
 
<langsyntaxhighlight lang="glee">Result:
1 2 3
1 2 4
Line 2,087 ⟶ 2,261:
2 3 5
2 4 5
3 4 5</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,118 ⟶ 2,292:
}
rc(0, 0)
}</langsyntaxhighlight>
{{out}}
<pre>[0 1 2]
Line 2,136 ⟶ 2,310:
===In General===
A recursive closure must be ''pre-declared''.
<langsyntaxhighlight lang="groovy">def comb
comb = { m, list ->
def n = list.size()
Line 2,145 ⟶ 2,319:
newlist += comb(m-1, sublist).collect { [list[k]] + it }
}
}</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">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() }</langsyntaxhighlight>
 
{{out}}
Line 2,181 ⟶ 2,355:
 
===Zero-based Integers===
<langsyntaxhighlight lang="groovy">def comb0 = { m, n -> comb(m, (0..<n)) }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">println "Choose out of 5 (zero-based):"
(0..3).each { i -> println "Choose ${i}:"; comb0(i, 5).each { println it }; println() }</langsyntaxhighlight>
 
{{out}}
Line 2,224 ⟶ 2,398:
 
===One-based Integers===
<langsyntaxhighlight lang="groovy">def comb1 = { m, n -> comb(m, (1..n)) }</langsyntaxhighlight>
 
Test program:
<langsyntaxhighlight lang="groovy">println "Choose out of 5 (one-based):"
(0..3).each { i -> println "Choose ${i}:"; comb1(i, 5).each { println it }; println() }</langsyntaxhighlight>
 
{{out}}
Line 2,271 ⟶ 2,445:
 
Straightforward, unoptimized implementation with divide-and-conquer:
<langsyntaxhighlight lang="haskell">comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb _ [] = []
comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs</langsyntaxhighlight>
 
In the induction step, either ''x'' is not in the result and the recursion proceeds with the rest of the list ''xs'', or it is in the result and then we only need ''m-1'' elements.
 
Shorter version of the above:
<langsyntaxhighlight lang="haskell">import Data.List (tails)
 
comb :: Int -> [a] -> [[a]]
comb 0 _ = [[]]
comb m l = [x:ys | x:xs <- tails l, ys <- comb (m-1) xs]</langsyntaxhighlight>
 
To generate combinations of integers between 0 and ''n-1'', use
 
<langsyntaxhighlight lang="haskell">comb0 m n = comb m [0..n-1]</langsyntaxhighlight>
 
Similar, for integers between 1 and ''n'', use
 
<langsyntaxhighlight lang="haskell">comb1 m n = comb m [1..n]</langsyntaxhighlight>
 
Another method is to use the built in ''Data.List.subsequences'' function, filter for subsequences of length ''m'' and then sort:
 
<langsyntaxhighlight lang="haskell">import Data.List (sort, subsequences)
comb m n = sort . filter ((==m) . length) $ subsequences [0..n-1]</langsyntaxhighlight>
 
And yet another way is to use the list monad to generate all possible subsets:
 
<langsyntaxhighlight lang="haskell">comb m n = filter ((==m . length) $ filterM (const [True, False]) [0..n-1]</langsyntaxhighlight>
 
===Dynamic Programming===
The first solution is inefficient because it repeatedly calculates the same subproblem in different branches of recursion. For example, <code>comb m (x1:x2:xs)</code> involves computing <code>comb (m-1) (x2:xs)</code> and <code>comb m (x2:xs)</code>, both of which (separately) compute <code>comb (m-1) xs</code>. To avoid repeated computation, we can use dynamic programming:
 
<langsyntaxhighlight lang="haskell">comb :: Int -> [a] -> [[a]]
comb m xs = combsBySize xs !! m
where
Line 2,316 ⟶ 2,490:
 
main :: IO ()
main = print $ comb 3 [0 .. 4]</langsyntaxhighlight>
{{Out}}
<pre>[[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]]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
return combinations(3,5,0)
end
Line 2,340 ⟶ 2,514:
end
 
link lists</langsyntaxhighlight>
 
The {{libheader|Icon Programming Library}} provides the core procedure [http://www.cs.arizona.edu/icon/library/src/procs/lists.icn lcomb in lists] written by Ralph E. Griswold and Richard L. Goerwitz.
<langsyntaxhighlight Iconlang="icon">procedure lcomb(L,i) #: list combinations
local j
 
Line 2,350 ⟶ 2,524:
else [L[j := 1 to *L - i + 1]] ||| lcomb(L[j + 1:0],i - 1)
 
end</langsyntaxhighlight>
{{out}}
<pre>3 combinations of 5 integers starting from 0
Line 2,366 ⟶ 2,540:
[ 1 3 4 ]
[ 2 3 4 ]</pre>
 
=={{header|IS-BASIC}}==
<lang IS-BASIC>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</lang>
 
=={{header|J}}==
Line 2,393 ⟶ 2,545:
===Library===
 
<syntaxhighlight lang ="j">require'stats'</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> 3 comb 5
0 1 2
0 1 3
Line 2,407 ⟶ 2,559:
1 2 4
1 3 4
2 3 4</langsyntaxhighlight>
 
All implementations here give that same result if given the same arguments.
 
===Iteration===
<langsyntaxhighlight lang="j">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.
)</langsyntaxhighlight>
 
another iteration version
<langsyntaxhighlight lang="j">comb2=: dyad define
d =. 1 + y - x
k =. >: |. i. d
Line 2,428 ⟶ 2,580:
end.
;{.z
)</langsyntaxhighlight>
 
===Recursion===
<langsyntaxhighlight lang="j">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.
)</langsyntaxhighlight>
The <code>M.</code> uses memoization (caching) which greatly reduces the running time. As a result, this is probably the fastest of the implementations here.
 
A less efficient but easier to understand recursion (similar to Python and Haskell).
<langsyntaxhighlight lang="j"> combr=: dyad define
if.(x=#y) +. x=1 do.
y
Line 2,444 ⟶ 2,596:
end.
)
</syntaxhighlight>
</lang>
You need to supply the "list" for example <code>i.5</code>
<code>
Line 2,452 ⟶ 2,604:
===Brute Force===
We can also generate all permutations and exclude those which are not properly sorted combinations. This is inefficient, but efficiency is not always important.
<langsyntaxhighlight lang="j">combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~)</langsyntaxhighlight>
 
=={{header|Java}}==
Line 2,458 ⟶ 2,610:
 
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.Collections;
import java.util.LinkedList;
 
Line 2,487 ⟶ 2,639:
return s;
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,493 ⟶ 2,645:
===Imperative===
 
<langsyntaxhighlight lang="javascript">function bitprint(u) {
var s="";
for (var n=0; u; ++n, u>>=1)
Line 2,510 ⟶ 2,662:
return s.sort();
}
comb(3,5)</langsyntaxhighlight>
 
Alternative recursive version using and an array of values instead of length:
{{trans|Python}}
 
<langsyntaxhighlight lang="javascript">function combinations(arr, k){
var i,
subI,
Line 2,540 ⟶ 2,692:
combinations(["Crosby", "Stills", "Nash", "Young"], 3);
// produces: [["Crosby", "Stills", "Nash"], ["Crosby", "Stills", "Young"], ["Crosby", "Nash", "Young"], ["Stills", "Nash", "Young"]]
</syntaxhighlight>
</lang>
 
===Functional===
Line 2,548 ⟶ 2,700:
Simple recursion:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
function comb(n, lst) {
Line 2,576 ⟶ 2,728:
}).join('\n');
 
})();</langsyntaxhighlight>
 
We can significantly improve on the performance of the simple recursive function by deriving a memoized version of it, which stores intermediate results for repeated use.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (n) {
 
// n -> [a] -> [[a]]
Line 2,625 ⟶ 2,777:
}).join('\n');
 
})(3);</langsyntaxhighlight>
 
 
{{Out}}
 
<syntaxhighlight lang="javascript">0 1 2
<lang JavaScript>0 1 2
0 1 3
0 1 4
Line 2,639 ⟶ 2,791:
1 2 4
1 3 4
2 3 4</langsyntaxhighlight>
 
 
====ES6====
Defined in terms of a recursive helper function:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,704 ⟶ 2,856:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4],
Line 2,710 ⟶ 2,862:
 
Or, defining combinations in terms of a more general subsequences function:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,800 ⟶ 2,952:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[[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]]</pre>
 
With recursions:
<langsyntaxhighlight JavaScriptlang="javascript">function combinations(k, arr, prefix = []) {
if (prefix.length == 0) arr = [...Array(arr).keys()];
if (k == 0) return [prefix];
Line 2,811 ⟶ 2,963:
combinations(k - 1, arr.slice(i + 1), [...prefix, v])
);
}</langsyntaxhighlight>
 
=={{header|jq}}==
combination(r) generates a stream of combinations of the input array.
The stream can be captured in an array as shown in the second example.
<langsyntaxhighlight lang="jq">def combination(r):
if r > length or r < 0 then empty
elif r == length then .
Line 2,824 ⟶ 2,976:
 
# select r integers from the set (0 .. n-1)
def combinations(n;r): [range(0;n)] | combination(r);</langsyntaxhighlight>
'''Example 1'''
combinations(5;3)
Line 2,846 ⟶ 2,998:
=={{header|Julia}}==
The <code>combinations</code> function in the <code>Combinatorics.jl</code> package generates an iterable sequence of the combinations that you can loop over. (Note that the combinations are computed on the fly during the loop iteration, and are not pre-computed or stored since there many be a very large number of them.)
<langsyntaxhighlight lang="julia">using Combinatorics
n = 4
m = 3
for i in combinations(0:n,m)
println(i')
end</langsyntaxhighlight>
{{out}}
<pre>[0 1 2]
Line 2,869 ⟶ 3,021:
 
If, on the other hand we wanted to show how it could be done in Julia, this recursive solution shows some potentials of Julia lang.
<langsyntaxhighlight lang="julia">##############################
# COMBINATIONS OF 3 OUT OF 5 #
##############################
Line 2,895 ⟶ 3,047:
 
combinations(1, 0)
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,909 ⟶ 3,061:
[3, 4, 5]
</pre>
 
===Iterator Solution===
Alternatively, Julia's Iterators can be used for a very nice solution for any collection.
<syntaxhighlight lang="julia">
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
</syntaxhighlight>
{{out}}
<pre>
julia> show(combinations([1,2,3,4,5], 3))
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 5], [1, 3, 5], [2, 3, 5], [1, 4, 5], [2, 4, 5], [3, 4, 5]]
</pre>
end
 
=={{header|K}}==
Recursive implementation:
 
<langsyntaxhighlight lang="k">comb:{[n;k]
f:{:[k=#x; :,x; :,/_f' x,'(1+*|x) _ !n]}
:,/f' !n
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
Translation from Emacs-lisp
<syntaxhighlight lang="scheme">
<lang Scheme>
 
{def comb
Line 2,941 ⟶ 3,124:
[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
 
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
===Recursion===
{{trans|Pascal}}
<langsyntaxhighlight lang="kotlin">class Combinations(val m: Int, val n: Int) {
private val combination = IntArray(m)
 
Line 2,970 ⟶ 3,153:
fun main(args: Array<String>) {
Combinations(3, 5)
}</langsyntaxhighlight>
 
{{out}}
Line 2,988 ⟶ 3,171:
===Lazy===
{{trans|C#}}
<langsyntaxhighlight lang="kotlin">import java.util.LinkedList
 
inline fun <reified T> combinations(arr: Array<T>, m: Int) = sequence {
Line 3,016 ⟶ 3,199:
combinations((1..n).toList().toTypedArray(), m).forEach { println(it.joinToString(separator = " ")) }
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,034 ⟶ 3,217:
=={{header|Lobster}}==
{{trans|Nim}}
<langsyntaxhighlight Lobsterlang="lobster">import std
 
// combi is an itertor that solves the Combinations problem for iota arrays as stated
Line 3,054 ⟶ 3,237:
i += 1
 
combi(5, 3): print(_)</langsyntaxhighlight>
{{out}}
<pre>[0, 1, 2]
Line 3,068 ⟶ 3,251:
 
{{trans|JavaScript}}
<langsyntaxhighlight Lobsterlang="lobster">import std
 
// comba solves the general problem for any values in an input array
Line 3,089 ⟶ 3,272:
var s = ""
combi(4, 3): s += (map(_) i: ["Crosby", "Stills", "Nash", "Young"][i]) + " "
print s</langsyntaxhighlight>
{{out}}
<pre>[[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]]
Line 3,097 ⟶ 3,280:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to comb :n :list
if :n = 0 [output [[]]]
if empty? :list [output []]
Line 3,103 ⟶ 3,286:
comb :n bf :list
end
print comb 3 [0 1 2 3 4]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
function map(f, a, ...) if a then return f(a), map(f, ...) end end
function incr(k) return function(a) return k > a and a or a+1 end end
Line 3,119 ⟶ 3,302:
 
for k, v in ipairs(combs(3, 5)) do print(unpack(v)) end
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Including a helper sub to export result to clipboard through a global variable (a temporary global variable)
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Global a$
Line 3,165 ⟶ 3,348:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,181 ⟶ 3,364:
 
===Step by Step===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module StepByStep {
Function CombinationsStep (a, nn) {
Line 3,227 ⟶ 3,410:
}
StepByStep
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
Line 3,255 ⟶ 3,438:
divert
 
comb(3,5)</langsyntaxhighlight>
 
=={{header|Maple}}==
This is built-in in Maple:
<langsyntaxhighlight Maplelang="maple">> combinat:-choose( 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]]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">combinations[n_Integer, m_Integer]/;m>= 0:=Union[Sort /@ Permutations[Range[0, n - 1], {m}]]</langsyntaxhighlight>
built-in function example
<langsyntaxhighlight Mathematicalang="mathematica">Subsets[Range[5], {2}]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Line 3,274 ⟶ 3,457:
 
Task Solution:
<langsyntaxhighlight MATLABlang="matlab">>> nchoosek((0:4),3)
 
ans =
Line 3,287 ⟶ 3,470:
1 2 4
1 3 4
2 3 4</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">next_comb(n, p, a) := block(
[a: copylist(a), i: p],
if a[1] + p = n + 1 then return(und),
Line 3,315 ⟶ 3,498:
[2, 3, 5],
[2, 4, 5],
[3, 4, 5]] */</langsyntaxhighlight>
 
=={{header|Modula-2}}==
{{trans|Pascal}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<langsyntaxhighlight lang="modula2">
MODULE Combinations;
FROM STextIO IMPORT
Line 3,357 ⟶ 3,540:
Generate(1);
END Combinations.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,373 ⟶ 3,556:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">iterator comb(m, n: int): seq[int] =
var c = newSeq[int](n)
for i in 0 ..< n: c[i] = i
Line 3,394 ⟶ 3,577:
 
for i in comb(5, 3):
echo i</langsyntaxhighlight>
{{out}}
<pre>@[0, 1, 2]
Line 3,409 ⟶ 3,592:
 
Another way, using a stack. Adapted from C#:
<langsyntaxhighlight lang="nim">iterator combinations(m: int, n: int): seq[int] =
 
var result = newSeq[int](n)
Line 3,430 ⟶ 3,613:
for i in combinations(5, 3):
echo i</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let combinations m n =
let rec c = function
| (0,_) -> [[]]
Line 3,448 ⟶ 3,631:
| hd :: tl -> print_int hd ; print_string " "; print_list tl
in List.iter print_list (combinations 3 5)
</syntaxhighlight>
</lang>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">nchoosek([0:4], 3)</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
{{trans|Julia}}
<syntaxhighlight lang="openedge/progress">
<lang OpenEdge/Progress>
define variable r as integer no-undo extent 3.
define variable m as integer no-undo initial 5.
Line 3,475 ⟶ 3,658:
 
combinations(1, 0).
</syntaxhighlight>
</lang>
{{out}}
0 1 2<br>
Line 3,490 ⟶ 3,673:
=={{header|Oz}}==
This can be implemented as a trivial application of finite set constraints:
<langsyntaxhighlight lang="oz">declare
fun {Comb M N}
proc {CombScript Comb}
Line 3,505 ⟶ 3,688:
end
in
{Inspect {Comb 3 5}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">Crv ( k, v, d ) = {
if( d == k,
print ( vecextract( v , "2..-2" ) )
Line 3,517 ⟶ 3,700:
}
 
combRV( n, k ) = Crv ( k, vector( n, X, X-1), 0 );</langsyntaxhighlight>
 
<langsyntaxhighlight lang="parigp">Cr ( c, z, b, n, k ) = {
if( z < b, print1( c, " " );
if( n>0, Cr( c+1, z , b* k \n, n-1, k - 1 ))
Line 3,535 ⟶ 3,718:
print
);
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="parigp">Ci( z, b, n, k ) = { local( c = 1 );
n--; k--;
while( k >= 0 ,
Line 3,561 ⟶ 3,744:
for( z = 0, bnk - 1,
Ci(z, b11, n, k ) );
}</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program Combinations;
const
Line 3,593 ⟶ 3,776:
begin
generate(1);
end.</langsyntaxhighlight>
 
{{out}}
Line 3,612 ⟶ 3,795:
The [https://metacpan.org/pod/ntheory ntheory] module has a combinations iterator that runs in lexicographic order.
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/forcomb/;
forcomb { print "@_\n" } 5,3</langsyntaxhighlight>
{{out}}
<pre>
Line 3,630 ⟶ 3,813:
[https://metacpan.org/pod/Algorithm::Combinatorics Algorithm::Combinatorics] also does lexicographic order and can return the whole array or an iterator:
{{libheader|Algorithm::Combinatorics}}
<langsyntaxhighlight lang="perl">use Algorithm::Combinatorics qw/combinations/;
my @c = combinations( [0..4], 3 );
print "@$_\n" for @c;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">use Algorithm::Combinatorics qw/combinations/;
my $iter = combinations([0..4],3);
while (my $c = $iter->next) {
print "@$c\n";
}</langsyntaxhighlight>
 
[https://metacpan.org/pod/Math::Combinatorics Math::Combinatorics] is another option but results will not be in lexicographic order as specified by the task.
Line 3,656 ⟶ 3,839:
The major <i>Perl5i</i> -isms are the implicit "autoboxing" of the intermediate resulting array into an array object, with the use of unshift() as a method, and the "func" keyword and signature.
Note that Perl can construct ranges of numbers or of letters, so it is natural to identify the characters as 'a' .. 'e'.
<syntaxhighlight lang="perl5i">
<lang Perl5i>
use perl5i::2;
 
Line 3,679 ⟶ 3,862:
 
say @$_ for combine( 3, ('a'..'e') );
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,697 ⟶ 3,880:
=={{header|Phix}}==
It does not get much simpler or easier than this. See [[Sudoku#Phix|Sudoku]] for a practical application of this algorithm
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">comb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">pool</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">needed</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">done</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">chosen</span><span style="color: #0000FF;">={})</span>
Line 3,712 ⟶ 3,895:
<span style="color: #000000;">comb</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,725 ⟶ 3,908:
{2,4,5}
{3,4,5}
</pre>
As of 1.0.2 there is a builtin combinations() function. Using a string here for simplicity and neater output, but it works with any sequence:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">combinations</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"12345"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">),</span><span style="color: #008000;">','</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
"123,124,125,134,135,145,234,235,245,345"
</pre>
 
Line 3,733 ⟶ 3,924:
Much slower than normal algorithm.
 
<langsyntaxhighlight lang="php">
<?php
 
Line 3,783 ⟶ 3,974:
 
?>
</syntaxhighlight>
</lang>
'''
Output:'''
Line 3,806 ⟶ 3,997:
===recursive===
 
<langsyntaxhighlight lang="php"><?php
 
function combinations_set($set = [], $size = 0) {
Line 3,854 ⟶ 4,045:
echo implode(", ", $combination), "\n";
}
</syntaxhighlight>
</lang>
 
Outputs:
Line 3,874 ⟶ 4,065:
=={{header|Picat}}==
===Recursion===
<langsyntaxhighlight Picatlang="picat">go =>
% Integers 1..K
N = 3,
Line 3,885 ⟶ 4,076:
comb1_(0, _X) = [[]].
comb1_(_M, []) = [].
comb1_(M, [X|Xs]) = [ [X] ++ Xs2 : Xs2 in comb1_(M-1, Xs) ] ++ comb1_(M, Xs).</langsyntaxhighlight>
 
{{out}}
Line 3,891 ⟶ 4,082:
 
===Using built-in power_set===
<langsyntaxhighlight Picatlang="picat">comb2(K, N) = sort([[J : J in I] : I in power_set(1..N), I.length == K]).</langsyntaxhighlight>
 
===Combinations from a list===
<langsyntaxhighlight Picatlang="picat">go3 =>
L = "abcde",
printf("comb3(%d,%w): %w\n",3,L,comb3(3,L)).
 
comb3(M, List) = [ [List[P[I]] : I in 1..P.length] : P in comb1(M,List.length)].</langsyntaxhighlight>
 
{{out}}
Line 3,905 ⟶ 4,096:
=={{header|PicoLisp}}==
{{trans|Scheme}}
<langsyntaxhighlight PicoLisplang="picolisp">(de comb (M Lst)
(cond
((=0 M) '(NIL))
Line 3,916 ⟶ 4,107:
(comb M (cdr Lst)) ) ) ) )
 
(comb 3 (1 2 3 4 5))</langsyntaxhighlight>
 
=={{header|Pop11}}==
Line 3,923 ⟶ 4,114:
The 'el_lst' parameter to 'do_combs' contains partial combination (list of numbers which were chosen in previous steps) in reverse order.
 
<langsyntaxhighlight lang="pop11">define comb(n, m);
lvars ress = [];
define do_combs(l, m, el_lst);
Line 3,939 ⟶ 4,130:
enddefine;
 
comb(5, 3) ==></langsyntaxhighlight>
 
=={{header|PowerShell}}==
An example of how PowerShell itself can translate C# code:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$source = @'
using System;
Line 3,979 ⟶ 4,170:
 
[Powershell.CSharp]::Combinations(3,5) | Format-Wide {$_} -Column 3 -Force
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,997 ⟶ 4,188:
The solutions work with SWI-Prolog <BR>
Solution with library clpfd : we first create a list of M elements, we say that the members of the list are numbers between 1 and N and there are in ascending order, finally we ask for a solution.
<langsyntaxhighlight lang="prolog">:- use_module(library(clpfd)).
 
comb_clpfd(L, M, N) :-
Line 4,003 ⟶ 4,194:
L ins 1..N,
chain(L, #<),
label(L).</langsyntaxhighlight>
{{out}}
<pre> ?- comb_clpfd(L, 3, 5), writeln(L), fail.
Line 4,018 ⟶ 4,209:
false.</pre>
Another solution :
<langsyntaxhighlight lang="prolog">comb_Prolog(L, M, N) :-
length(L, M),
fill(L, 1, N).
Line 4,028 ⟶ 4,219:
H1 is H + 1,
fill(T, H1, Max).
</syntaxhighlight>
</lang>
with the same output.
 
===List comprehension===
Works with SWI-Prolog, library '''clpfd''' from '''Markus Triska''', and list comprehension (see [[List comprehensions]] ).
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
comb_lstcomp(N, M, V) :-
V <- {L & length(L, N), L ins 1..M & all_distinct(L), chain(L, #<), label(L)}.
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,045 ⟶ 4,236:
 
=={{header|Pure}}==
<langsyntaxhighlight lang="pure">comb m n = comb m (0..n-1) with
comb 0 _ = [[]];
comb _ [] = [];
Line 4,051 ⟶ 4,242:
end;
 
comb 3 5;</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure.s Combinations(amount, choose)
NewList comb.s()
; all possible combinations with {amount} Bits
Line 4,087 ⟶ 4,278:
EndProcedure
 
Debug Combinations(5, 3)</langsyntaxhighlight>
 
=={{header|Pyret}}==
<langsyntaxhighlight lang="pyret">
 
fun combos<a>(lst :: List<a>, size :: Number) -> List<List<a>>:
Line 4,196 ⟶ 4,387:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
Starting from Python 2.6 and 3.0 you have a pre-defined function that returns an iterator. Here we turn the result into a list for easy printing:
<langsyntaxhighlight lang="python">>>> from itertools import combinations
>>> list(combinations(range(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)]</langsyntaxhighlight>
 
Earlier versions could use functions like the following:
{{trans|E}}
<langsyntaxhighlight lang="python">def comb(m, lst):
if m == 0: return [[]]
return [[x] + suffix for i, x in enumerate(lst)
for suffix in comb(m - 1, lst[i + 1:])]</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="python">>>> comb(3, range(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]]</langsyntaxhighlight>
{{trans|Haskell}}
<langsyntaxhighlight lang="python">def comb(m, s):
if m == 0: return [[]]
if s == []: return []
return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])
 
print comb(3, range(5))</langsyntaxhighlight>
 
A slightly different recursion version
<langsyntaxhighlight lang="python">
def comb(m, s):
if m == 1: return [[x] for x in s]
Line 4,229 ⟶ 4,420:
return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Line 4,235 ⟶ 4,426:
===Bit Bashing===
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 swap
[ dup 0 != while
dup 1 & if
Line 4,282 ⟶ 4,473:
3 5 comb
sortcombs
witheach [ witheach [ echo sp ] cr ]</langsyntaxhighlight>
 
{{out}}
Line 4,299 ⟶ 4,490:
===Iterative===
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is comb.stack
[ stack ] is comb.items
[ stack ] is comb.required
Line 4,329 ⟶ 4,520:
 
3 5 comb
witheach [ witheach [ echo sp ] cr ]</langsyntaxhighlight>
 
{{out}}
Line 4,348 ⟶ 4,539:
Can be used with <code>comb</code>, and is general purpose.
 
<langsyntaxhighlight Quackerylang="quackery"> [ dup size dip
[ witheach
[ over swap peek swap ] ]
Line 4,363 ⟶ 4,554:
$ "zero one two three four" nest$
' [ 4 3 1 0 1 4 3 ] arrange
witheach [ echo$ sp ] </langsyntaxhighlight>
 
{{out}}
Line 4,381 ⟶ 4,572:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">print(combn(0:4, 3))</langsyntaxhighlight>
Combinations are organized per column,
so to provide an output similar to the one in the task text, we need the following:
<langsyntaxhighlight Rlang="r">r <- combn(0:4, 3)
for(i in 1:choose(5,3)) print(r[,i])</langsyntaxhighlight>
 
=={{header|Racket}}==
{{trans|Haskell}}
 
<langsyntaxhighlight lang="racket">
(define sublists
(match-lambda**
Line 4,400 ⟶ 4,591:
(define (combinations n m)
(sublists n (range m)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,421 ⟶ 4,612:
{{works with|rakudo|2015.12}}
There actually is a builtin:
<syntaxhighlight lang="raku" perl6line>.say for combinations(5,3);</langsyntaxhighlight>
{{out}}
<pre>(0 1 2)
Line 4,435 ⟶ 4,626:
 
Here is an iterative routine with the same output:
<syntaxhighlight lang="raku" perl6line>sub combinations(Int $n, Int $k) {
return ([],) unless $k;
return if $k > $n || $n <= 0;
Line 4,449 ⟶ 4,640:
}
}
.say for combinations(5,3);</langsyntaxhighlight>
 
=={{header|REXX}}==
===Version 1===
This REXX program supports up to &nbsp; 100 &nbsp; symbols &nbsp; (one symbol for each "thing").
 
Line 4,457 ⟶ 4,649:
 
The symbol list could be extended by added any unique viewable symbol &nbsp; (character).
<langsyntaxhighlight lang="rexx">/*REXX program displays combination sets for X things taken Y at a time. */
parseParse argArg xthings ysize $chars . /* get optional arguments from the C.L.command line */
If things='?' Then Do
if x=='' | x=="," then x= 5 /*No X specified? Then use default.*/
Say 'rexx combi things size characters'
if y=='' | y=="," then y= 3; oy= y; y= abs(y) /* " Y " " " " */
Say ' defaults: 5 3 123456789...'
if $=='' | $=="," then $='123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
Say 'example rexx combi , , xyzuvw'
"~!@#$%^&*()_+`{}|[]\:;<>?,./█┌┐└┘±≥≤≈∙" /*some extended chars*/
Say 'size<0 shows only the number of possible combinations'
/* [↑] No $ specified? Use default.*/
Exit
if y>x then do; say y " can't be greater than " x; exit 1; end
End
say "────────────" x ' things taken ' y " at a time:"
If things==''|things=="," Then things=5 /* No things specified? Then use default*/
say "────────────" combN(x,y) ' combinations.'
If size=='' |size=="," Then size=3 /* No size specified? Then use default*/
exit /*stick a fork in it, we're all done. */
If chars==''|chars=="," Then /* No chars specified? Then Use default*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
chars='123456789abcdefghijklmnopqrstuvwxyz'||,
combN: procedure expose $ oy; parse arg x,y; xp= x+1; xm= xp-y; !.= 0
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'||,
if x=0 | y=0 then return 'no'
"~!@#chars%^&*()_+`{}|[]\:;<>?,./¦++++±==˜·" /*some extended chars */
do i=1 for y; !.i= i
 
end /*i*/
show_details=sign(size) do/* j=-1;: Don't L=show details */
size=abs(size)
do d=1 for y; L= L substr($, !.d, 1)
If things<size Then
end /*d*/
Call exit 'Not enough things ('things') for size ('size').'
if oy>0 then say L; !.y= !.y + 1 /*don't show if OY<0 */
Say '------------' things 'things taken' size 'times at a time:'
if !.y==xp then if .combN(y-1) then leave
Say '------------' combn(things,size) 'combinations.'
end /*j*/
Exit /* stick a fork in it, we're all */
return j
/*-------------------------------------------------------------------------------*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
combn: Procedure Expose chars show_details
.combN: procedure expose !. y xm; parse arg d; if d==0 then return 1; p= !.d
Parse Arg things,size
do u=d to y; !.u= p+1; if !.u==xm+u then return .combN(u-1); p= !.u
thingsp=things+1
end /*u*/ /* ↑ */
thingsm=thingsp-size
return 0 /*recursive call──►──────┘ */</lang>
index.=0
If things=0|size=0 Then
Return 'no'
Do i=1 For size
index.i=i
End
done=0
Do combi=1 By 1 Until done
combination=''
Do d=1 To size
combination=combination substr(chars,index.d,1)
End
If show_details=1 Then
Say combination
index.size=index.size+1
If index.size==thingsp Then
done=.combn(size-1)
End
Return combi
/*---------------------------------------------------------------------------------*/
.combn: Procedure Expose index. size thingsm
Parse Arg d
--Say '.combn' d thingsm show()
If d==0 Then
Return 1
p=index.d
Do u=d To size
index.u=p+1
If index.u==thingsm+u Then
Return .combn(u-1)
p=index.u
End
Return 0
 
show:
list=''
Do k=1 To size
list=list index.k
End
Return list
 
exit:
Say '*****error*****' arg(1)
Exit 13
</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 5 &nbsp; 3 &nbsp; 01234 </tt>}}
<pre>
────────────------------ 5 things taken 3 at a time:
0 1 2
0 1 3
Line 4,498 ⟶ 4,735:
1 3 4
2 3 4
────────────------------ 10 combinations.
</pre>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 5 &nbsp; 3 &nbsp; abcde </tt>}}
<pre>
────────────------------ 5 things taken 3 at a time:
a b c
a b d
Line 4,513 ⟶ 4,750:
b d e
c d e
────────────------------ 10 combinations.
</pre>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 44 &nbsp; 0 </tt>}}
<pre>
────────────------------ 44 things taken 0 at a time:
────────────------------ no combinations.
</pre>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 52 &nbsp; -5 </tt>}}
<pre>
────────────------------ 52 things taken 5 at a time:
────────────------------ 2598960 combinations.
</pre>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 5 &nbsp; -8 </tt>}}
<pre>
*****error***** Not enough things (5) for size (8).
</pre>
===Version 2===
{{trans|Java}}
<syntaxhighlight lang="rexx">/*REXX program displays combination sets for X things taken Y at a time. */
Parse Arg things size characters
If things='?' Then Do
Say 'rexx combi2 things size characters'
Say ' defaults: 5 3 123456789...'
Say 'example rexx combi2 , , xyzuvw'
Say 'size<0 shows only the number of possible combinations'
Exit
End
If things==''|things=="," Then things=5 /* No things specified? Then use default*/
If size=='' |size=="," Then size=3 /* No size specified? Then use default*/
Numeric Digits 20
show=sign(size)
size=abs(size)
If things<size Then
Call exit 'Not enough things ('things') for size ('size').' Say '----------' things 'things taken' size 'at a time:'
n=2**things-1
nc=0
Do u=1 to n
nc=nc+combinations(u)
End
Say '------------' nc 'combinations.'
Exit
combinations: Procedure Expose things size characters show
Parse Arg u
nc=0
bu=x2b(d2x(u))
bu1=space(translate(bu,' ',0),0)
If length(bu1)=size Then Do
ub=reverse(bu)
res=''
Do i=1 To things
If characters<>'' then
c=substr(characters,i,1)
Else
c=i
If substr(ub,i,1)=1 Then res=res c
End
If show=1 then
Say res
Return 1
End
Else
Return 0
exit:
Say '*****error*****' arg(1)
Exit 13 </syntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Combinations
 
Line 4,600 ⟶ 4,890:
next
return aList
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,613 ⟶ 4,903:
[2 4 5]
[3 4 5]
</pre>
 
=={{header|RPL}}==
{{trans|BASIC}}
{{works with|HP|48SX}}
≪ → currcomb start stop depth
≪ '''WHILE''' start stop ≤ '''REPEAT'''
currcomb start +
1 'start' STO+
'''IF''' depth '''THEN'''
start stop depth 1 - <span style="color:blue">GENCOMB</span> '''END'''
'''END'''
≫ ≫ '<span style="color:blue">GENCOMB</span>' STO
{ } 0 4 ROLL 1 - 4 ROLL 1 - <span style="color:blue">GENCOMB</span>
≫ '<span style="color:blue">COMBS</span>' STO
 
5 3 <span style="color:blue">COMBS</span>
{{out}}
<pre>
10: { 0 1 2 }
9: { 0 1 3 }
8: { 0 1 4 }
7: { 0 2 3 }
6: { 0 2 4 }
5: { 0 3 4 }
4: { 1 2 3 }
3: { 1 2 4 }
2: { 1 3 4 }
1: { 2 3 4 }
</pre>
 
=={{header|Ruby}}==
{{works with|Ruby|1.8.7+}}
<langsyntaxhighlight lang="ruby">def comb(m, n)
(0...n).to_a.combination(m).to_a
end
 
comb(3, 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]]</langsyntaxhighlight>
 
=={{header|Rust}}==
{{works with|Rust|0.9}}
<langsyntaxhighlight lang="rust">
fn comb<T: std::fmt::Default>(arr: &[T], n: uint) {
let mut incl_arr: ~[bool] = std::vec::from_elem(arr.len(), false);
Line 4,656 ⟶ 4,977:
comb(arr2, 3);
}
</syntaxhighlight>
</lang>
 
{{works with|Rust|1.26}}
<langsyntaxhighlight lang="rust">
struct Combo<T> {
data_len: usize,
Line 4,722 ⟶ 5,043:
}
}
</syntaxhighlight>
</lang>
 
{{works with|Rust|1.47|}}
<langsyntaxhighlight lang="rust">
fn comb<T>(slice: &[T], k: usize) -> Vec<Vec<T>>
where
Line 4,750 ⟶ 5,071:
return result;
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">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 {
Line 4,760 ⟶ 5,081:
case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail)
}
}</langsyntaxhighlight>
 
Usage:
Line 4,771 ⟶ 5,092:
 
Lazy version using iterators:
<langsyntaxhighlight lang="scala"> def combs[A](n: Int, l: List[A]): Iterator[List[A]] = n match {
case _ if n < 0 || l.lengthCompare(n) < 0 => Iterator.empty
case 0 => Iterator(List.empty)
Line 4,778 ⟶ 5,099:
case x :: xs => combs(n - 1, xs).map(x :: _)
})
}</langsyntaxhighlight>
Usage:
<pre>
Line 4,787 ⟶ 5,108:
===Dynamic programming===
Adapted from Haskell version:
<langsyntaxhighlight lang="scala"> def combs[A](n: Int, xs: List[A]): Stream[List[A]] =
combsBySize(xs)(n)
 
Line 4,802 ⟶ 5,123:
 
def f[A](x: A, xsss: Stream[Stream[List[A]]]): Stream[Stream[List[A]]] =
Stream.empty #:: xsss.map(_.map(x :: _))</langsyntaxhighlight>
Usage:
<pre>
Line 4,811 ⟶ 5,132:
===Using Scala Standard Runtime Library===
====Scala REPL====
<langsyntaxhighlight lang="scala">scala>(0 to 4).combinations(3).toList
res0: List[scala.collection.immutable.IndexedSeq[Int]] = List(Vector(0, 1, 2), Vector(0, 1, 3), Vector(0, 1, 4), Vector(0, 2, 3), Vector(0, 2, 4), Vector(0, 3, 4), Vector(1, 2, 3), Vector(1, 2, 4), Vector(1, 3, 4), Vector(2, 3, 4))</langsyntaxhighlight>
====Other environments====
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/DH34cqq/0 ScalaFiddle (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/bwADub2XR8eu6bVVDbQw7g Scastie (JVM)].
Line 4,818 ⟶ 5,139:
=={{header|Scheme}}==
Like the Haskell code:
<langsyntaxhighlight lang="scheme">(define (comb m lst)
(cond ((= m 0) '(()))
((null? lst) '())
Line 4,825 ⟶ 5,146:
(comb m (cdr lst))))))
 
(comb 3 '(0 1 2 3 4))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: combinations is array array integer;
Line 4,862 ⟶ 5,183:
writeln;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 4,879 ⟶ 5,200:
 
=={{header|SETL}}==
<langsyntaxhighlight SETLlang="setl">print({0..4} npow 3);</langsyntaxhighlight>
 
=={{header|Sidef}}==
 
===Built-in===
<langsyntaxhighlight lang="ruby">combinations(5, 3, {|*c| say c })</langsyntaxhighlight>
 
===Recursive===
 
{{trans|Perl5i}}
<langsyntaxhighlight lang="ruby">func combine(n, set) {
 
set.len || return []
Line 4,905 ⟶ 5,226:
}
 
combine(3, @^5).each {|c| say c }</langsyntaxhighlight>
 
===Iterative===
<langsyntaxhighlight lang="ruby">func forcomb(callback, n, k) {
 
if (k == 0) {
Line 4,938 ⟶ 5,259:
}
 
forcomb({|c| say c }, 5, 3)</langsyntaxhighlight>
{{out}}
<pre>
Line 4,956 ⟶ 5,277:
{{works with|Pharo}}
{{works with|Squeak}}
<langsyntaxhighlight lang="smalltalk">
(0 to: 4) combinations: 3 atATimeDo: [ :x | Transcript cr; show: x printString].
 
Line 4,970 ⟶ 5,291:
#(1 3 4)
#(2 3 4)"
</syntaxhighlight>
</lang>
 
=={{header|SPAD}}==
Line 4,976 ⟶ 5,297:
{{works with|OpenAxiom}}
{{works with|Axiom}}
<syntaxhighlight lang="spad">
<lang SPAD>
[reverse subSet(5,3,i)$SGCF for i in 0..binomial(5,3)-1]
Line 4,983 ⟶ 5,304:
[1,3,4], [2,3,4]]
Type: List(List(Integer))
</syntaxhighlight>
</lang>
 
[http://fricas.github.io/api/SymmetricGroupCombinatoricFunctions.html?highlight=choose SGCF]
==> SymmetricGroupCombinatoricFunctions
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "combinations" )
@( description, "Given non-negative integers m and n, generate all size m" )
@( description, "combinations of the integers from 0 to n-1 in sorted" )
@( description, "order (each combination is sorted and the entire table" )
@( description, "is sorted" )
@( see_also, "http://rosettacode.org/wiki/Combinations" )
@( author, "Ken O. Burtch" );
 
pragma restriction( no_external_commands );
 
procedure combinations is
number_of_items : constant natural := 3;
max_item_value : constant natural := 5;
 
-- get_first_combination
-- return the first combination (e.g. 0,1,2 for 3 items)
 
function get_first_combination return string is
c : string;
begin
for i in 1..number_of_items loop
c := @ & strings.image( natural( i-1 ) );
end loop;
return c;
end get_first_combination;
 
-- get_last_combination
-- return the highest value (e.g. 4,4,4 for 3 items
-- with a maximum value of 5).
 
function get_last_combination return string is
c : string;
begin
for i in 1..number_of_items loop
c := @ & strings.image( max_item_value-1 );
end loop;
return c;
end get_last_combination;
 
combination : string := get_first_combination;
last_combination : constant string := get_last_combination;
 
item : natural; -- a number from the combination
bad : boolean; -- true if we know a value is too big
s : string; -- a temp string for deleting leading space
 
begin
put_line( combination );
while combination /= last_combination loop
 
-- the combination is 3 numbers with leading spaces
-- so the field positions start at 2 (1 is a null string)
 
for i in reverse 1..number_of_items loop
item := numerics.value( strings.field( combination, i+1, ' ') );
if item < max_item_value-1 then
item := @+1;
s := strings.image( item );
s := strings.delete( s, 1, 1 );
strings.replace( combination, i+1, s, ' ' );
bad := false;
for j in i+1..number_of_items loop
item := numerics.value( strings.field( combination, j, ' ') );
if item < max_item_value-1 then
item := @+1;
s := strings.image( item );
s := strings.delete( s, 1, 1 );
strings.replace( combination, j+1, s, ' ' );
else
bad;
end if;
end loop;
exit;
end if;
end loop;
if not bad then
put_line( combination );
end if;
end loop;
end combinations;</syntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun comb (0, _ ) = [[]]
| comb (_, [] ) = []
| comb (m, x::xs) = map (fn y => x :: y) (comb (m-1, xs)) @
comb (m, xs)
;
comb (3, [0,1,2,3,4]);</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">program combin
tempfile cp
tempvar k
Line 5,009 ⟶ 5,414:
}
sort `1'*
end</langsyntaxhighlight>
 
'''Example'''
 
<langsyntaxhighlight lang="stata">. set obs 5
. gen a=_n
. combin a 3
Line 5,032 ⟶ 5,437:
9. | 2 4 5 |
10. | 3 4 5 |
+--------------+</langsyntaxhighlight>
=== Mata ===
<langsyntaxhighlight lang="stata">function combinations(n,k) {
a = J(comb(n,k),k,.)
u = 1..k
Line 5,047 ⟶ 5,452:
}
 
combinations(5,3)</langsyntaxhighlight>
 
'''Output'''
Line 5,066 ⟶ 5,471:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func addCombo(prevCombo: [Int], var pivotList: [Int]) -> [([Int], [Int])] {
 
return (0..<pivotList.count)
Line 5,085 ⟶ 5,490:
}
 
println(combosOfLength(5, 3))</langsyntaxhighlight>
{{out}}
<pre>[[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]]</pre>
Line 5,091 ⟶ 5,496:
=={{header|Tcl}}==
ref[http://wiki.tcl.tk/2553]
<langsyntaxhighlight lang="tcl">proc comb {m n} {
set set [list]
for {set i 0} {$i < $n} {incr i} {lappend set $i}
Line 5,111 ⟶ 5,516:
}
 
comb 3 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}</langsyntaxhighlight>
 
=={{header|TXR}}==
Line 5,119 ⟶ 5,524:
Combinations and permutations are produced in lexicographic order (except in the case of hashes).
 
<langsyntaxhighlight lang="txrlisp">(defun comb-n-m (n m)
(comb (range* 0 n) m))
 
(put-line `3 comb 5 = @(comb-n-m 5 3)`)</langsyntaxhighlight>
 
{{out|Run}}
Line 5,128 ⟶ 5,533:
<pre>$ txr combinations.tl
3 comb 5 = ((0 1 2) (0 1 3) (0 1 4) (0 2 3) (0 2 4) (0 3 4) (1 2 4) (1 3 4) (2 3 4))</pre>
 
=={{header|uBasic/4tH}}==
{{Trans|C}}
<syntaxhighlight lang="qbasic">o = 1
Proc _Comb(5, 3, 0, 0)
End
 
_Comb
Param (4)
If a@ < b@ + d@ Then Return
 
If b@ = 0 Then
For d@ = 0 To a@-1
If AND(c@, SHL(o, d@)) Then Print d@;" "; : Fi
Next
Print : Return
EndIf
 
Proc _Comb(a@, b@ - 1, OR(c@, SHL(o, d@)), d@ + 1)
Proc _Comb(a@, b@, c@, d@ + 1)
Return</syntaxhighlight>
{{Out}}
<pre>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
 
0 OK, 0:33</pre>
 
=={{header|Ursala}}==
Most of the work is done by the standard library function <code>choices</code>, whose implementation is shown here for the sake of comparison with other solutions,
<langsyntaxhighlight Ursalalang="ursala">choices = ^(iota@r,~&l); leql@a^& ~&al?\&! ~&arh2fabt2RDfalrtPXPRT</langsyntaxhighlight>
where <code>leql</code> is the predicate that compares list lengths. The main body of the algorithm (<code>~&arh2fabt2RDfalrtPXPRT</code>) concatenates the results of two recursive calls, one of which finds all combinations of the required size from the tail of the list, and the other of which finds all combinations of one less size from the tail, and then inserts the head into each.
<code>choices</code> generates combinations of an arbitrary set but
not necessarily in sorted order, which can be done like this.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
combinations = @rlX choices^|(iota,~&); -< @p nleq+ ==-~rh</langsyntaxhighlight>
* The sort combinator (<code>-<</code>) takes a binary predicate to a function that sorts a list in order of that predicate.
* The predicate in this case begins by zipping its two arguments together with <code>@p</code>.
Line 5,146 ⟶ 5,586:
* The overall effect of using everything starting from the <code>@p</code> as the predicate to a sort combinator is therefore to sort a list of lists of natural numbers according to the order of the numbers in the first position where they differ.
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nLL
 
example = combinations(3,5)</langsyntaxhighlight>
{{out}}
<pre><
Line 5,164 ⟶ 5,604:
=={{header|V}}==
like scheme (using variables)
<langsyntaxhighlight lang="v">[comb [m lst] let
[ [m zero?] [[[]]]
[lst null?] [[]]
[true] [m pred lst rest comb [lst first swap cons] map
m lst rest comb concat]
] when].</langsyntaxhighlight>
 
Using destructuring view and stack not *pure at all
<langsyntaxhighlight lang="v">[comb
[ [pop zero?] [pop pop [[]]]
[null?] [pop pop []]
[true] [ [m lst : [m pred lst rest comb [lst first swap cons] map
m lst rest comb concat]] view i ]
] when].</langsyntaxhighlight>
 
Pure concatenative version
<langsyntaxhighlight lang="v">[comb
[2dup [a b : a b a b] view].
[2pop pop pop].
Line 5,187 ⟶ 5,627:
[null?] [2pop []]
[true] [2dup [pred] dip uncons swapd comb [cons] map popd rollup rest comb concat]
] when].</langsyntaxhighlight>
 
Using it
Line 5,194 ⟶ 5,634:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Explicit
Option Base 0
'Option Base 1
Line 5,257 ⟶ 5,697:
Transposition = T
Erase T
End Function</langsyntaxhighlight>
{{Out}}
If Option Base 0 :
Line 5,282 ⟶ 5,722:
3 4 5</pre>
{{trans|Phix}}
<langsyntaxhighlight lang="vb">Private Sub comb(ByVal pool As Integer, ByVal needed As Integer, Optional ByVal done As Integer = 0, Optional ByVal chosen As Variant)
If needed = 0 Then '-- got a full set
For Each x In chosen: Debug.Print x;: Next x
Line 5,305 ⟶ 5,745:
Public Sub main()
comb 5, 3
End Sub</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function Dec2Bin(n)
q = n
Line 5,349 ⟶ 5,789:
'Testing with n = 5 / k = 3
Call Combination(5,3)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 5,367 ⟶ 5,807:
=={{header|Wren}}==
{{libheader|Wren-perm}}
<langsyntaxhighlight ecmascriptlang="wren">import "./perm" for Comb
 
var fib = Fiber.new { Comb.generate((0..4).toList, 3) }
Line 5,374 ⟶ 5,814:
if (!c) return
System.print(c)
}</langsyntaxhighlight>
 
{{out}}
Line 5,391 ⟶ 5,831:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11;
def M=3, N=5;
int A(N-1);
Line 5,409 ⟶ 5,849:
];
 
Combos(0, 0)</langsyntaxhighlight>
 
{{out}}
Line 5,427 ⟶ 5,867:
=={{header|zkl}}==
{{trans|OCaml}}
<langsyntaxhighlight lang="zkl">fcn comb(k,seq){ // no repeats, seq is finite
seq=seq.makeReadOnly(); // because I append to parts of seq
fcn(k,seq){
Line 5,435 ⟶ 5,875:
.extend(self.fcn(k,seq[1,*]));
}(k,seq);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">comb(3,"abcde".split("")).apply("concat")</langsyntaxhighlight>
{{out}}<pre>L("abc","abd","abe","acd","ace","ade","bcd","bce","bde","cde")</pre>
Anonymous user