Ecco una funzione ricorsiva scritta in GAP (vedi http://www.gap-system.org/)
combinazioni := function (n,k)
local comb, smallercombs, i, tmp, tmpcomb, x, tmpresult;
if (n<k or k<0 or n<0) then
return [];
elif k=0 then
return [[]];
fi;
comb:=[];
smallercombs:=combinazioni(n-1,k-1);
for i in [1..n-k+1] do
for tmp in smallercombs do
tmpcomb:=ShallowCopy(tmp);
if tmpcomb<>[] then
for x in [1..Length(tmpcomb)] do
tmpcomb[x]:= tmpcomb[x]+i;
od;
fi;
tmpresult:=[i];
Append(tmpresult,tmpcomb);
Add(comb,tmpresult);
od;
od;
return comb;
end;
Con un esempio di output:
gap> combinazioni(6,4);
[ [ 1, 2, 3, 4 ], [ 1, 2, 3, 5 ], [ 1, 2, 3, 6 ], [ 1, 2, 4, 5 ],
[ 1, 2, 4, 6 ], [ 1, 2, 4, 7 ], [ 1, 2, 5, 6 ], [ 1, 2, 5, 7 ],
[ 1, 2, 5, 8 ], [ 1, 3, 4, 5 ], [ 1, 3, 4, 6 ], [ 1, 3, 4, 7 ],
[ 1, 3, 5, 6 ], [ 1, 3, 5, 7 ], [ 1, 3, 5, 8 ], [ 1, 3, 6, 7 ],
[ 1, 3, 6, 8 ], [ 1, 3, 6, 9 ], [ 1, 4, 5, 6 ], [ 1, 4, 5, 7 ],
[ 1, 4, 5, 8 ], [ 1, 4, 6, 7 ], [ 1, 4, 6, 8 ], [ 1, 4, 6, 9 ],
[ 1, 4, 7, 8 ], [ 1, 4, 7, 9 ], [ 1, 4, 7, 10 ], [ 2, 3, 4, 5 ],
[ 2, 3, 4, 6 ], [ 2, 3, 4, 7 ], [ 2, 3, 5, 6 ], [ 2, 3, 5, 7 ],
[ 2, 3, 5, 8 ], [ 2, 3, 6, 7 ], [ 2, 3, 6, 8 ], [ 2, 3, 6, 9 ],
[ 2, 4, 5, 6 ], [ 2, 4, 5, 7 ], [ 2, 4, 5, 8 ], [ 2, 4, 6, 7 ],
[ 2, 4, 6, 8 ], [ 2, 4, 6, 9 ], [ 2, 4, 7, 8 ], [ 2, 4, 7, 9 ],
[ 2, 4, 7, 10 ], [ 2, 5, 6, 7 ], [ 2, 5, 6, 8 ], [ 2, 5, 6, 9 ],
[ 2, 5, 7, 8 ], [ 2, 5, 7, 9 ], [ 2, 5, 7, 10 ], [ 2, 5, 8, 9 ],
[ 2, 5, 8, 10 ], [ 2, 5, 8, 11 ], [ 3, 4, 5, 6 ], [ 3, 4, 5, 7 ],
[ 3, 4, 5, 8 ], [ 3, 4, 6, 7 ], [ 3, 4, 6, 8 ], [ 3, 4, 6, 9 ],
[ 3, 4, 7, 8 ], [ 3, 4, 7, 9 ], [ 3, 4, 7, 10 ], [ 3, 5, 6, 7 ],
[ 3, 5, 6, 8 ], [ 3, 5, 6, 9 ], [ 3, 5, 7, 8 ], [ 3, 5, 7, 9 ],
[ 3, 5, 7, 10 ], [ 3, 5, 8, 9 ], [ 3, 5, 8, 10 ], [ 3, 5, 8, 11 ],
[ 3, 6, 7, 8 ], [ 3, 6, 7, 9 ], [ 3, 6, 7, 10 ], [ 3, 6, 8, 9 ],
[ 3, 6, 8, 10 ], [ 3, 6, 8, 11 ], [ 3, 6, 9, 10 ], [ 3, 6, 9, 11 ],
[ 3, 6, 9, 12 ] ]
Post by El GioppinhoVorrei scrivere un programma che calcoli tutte le combinazioni semplici
possibili in un insieme di n numeri, presi k alla volta senza ripetizioni.
n!
---------
k! (n-k)!
Il programma dovrebbe calcolare tutte le varie combinazioni possibili, ad
1-2
1-3
1-4
2-3
2-4
3-4
senza dare combinazioni tipo 2-1, visto che l'ordine non è importante (c'è
già 1-2).
Purtroppo non riesco a definire il procedimento ricorsivo quando k>=3,
potete aiutarmi ?