Combinations: Difference between revisions

Line 3,871:
2, 3, 4
</pre>
 
=={{header|Picat}}==
<lang Picat>import util. % for power_set
 
go =>
% Integers 1..K
N = 3,
K = 5,
printf("comb1(3,5): %w\n", comb1(N,K)),
printf("comb2(3,5): %w\n", comb2(N,K)),
 
% Combinations of elements in a list
L = "abcde",
printf("comb1(%d,%w): %w\n",3,L,comb3(3,L)),
 
nl.
 
% Recursive (numbers)
comb1(M,N) = comb1_(M, 1..N).
comb1_(0, _X) = [[]].
comb1_(_M, []) = [].
comb1_(M, [X|Xs]) = [ [X] ++ Xs2 : Xs2 in comb1_(M-1, Xs) ] ++ comb1_(M, Xs).
 
% Using built-in power_set (numbers)
comb2(K, N) = sort([[J : J in I] : I in power_set(1..N), I.length == K]).
 
% combinations from a list
comb3(M, List) = [ [List[P[I]] : I in 1..P.length] : P in comb1(M,List.length)].</lang>
 
Output:
<pre>comb1(3,5): [[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]]
comb2(3,5): [[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]]
comb1(3,abcde): [abc,abd,abe,acd,ace,ade,bcd,bce,bde,cde]</pre>
 
=={{header|PicoLisp}}==
495

edits