seizetheday
seizetheday

Reputation: 333

How to implement combinations of a list

All

I need to get the combinations and permutations of a list.

A function have been implemented for permutations.

perm:{[N;l]$[N=1;l;raze .z.s[N-1;l]{x,/:y except x}\:l]}

However, I have no idea about combinations, just like this:

l: 1 2 3
comb[2;l]
1 2
1 3
2 3

l: 1 2 3 4
comb[3;l]
1 2 3
1 2 4
1 3 4
2 3 4

Thanks!

Upvotes: 0

Views: 2082

Answers (2)

Rahul
Rahul

Reputation: 3969

One option is to use your permutation function like this:

q) comb:{[N;l]  distinct asc each  perm[N;l] }

q)l: 1 2 3 4
q) comb[3;l]

output:

1 2 3

1 2 4

1 3 4

2 3 4

Note: This will change the order of elements because of asc. So if your list should have (1 3 2) in answer, it will give (1 2 3).

To maintain order, use any other function/logic in place of asc to filter duplicate elements in sets (ex: (1 2 3) and (1 3 2) are duplicates).

Upvotes: 0

WooiKent Lee
WooiKent Lee

Reputation: 1311

From your solution, you can do:

q)comb:{[N;l]$[N=1;l;raze .z.s[N-1;l]{x,/:y where y>max x}\:l]}
q)comb[2;1 2 3]
1 2
1 3
2 3

Another approach using over:

q)perm:{{raze x{x,/:y except x}\:y}[;y]/[x-1;y]}
q)comb:{{raze x{x,/:y where y>max x}\:y}[;y]/[x-1;y]}

Upvotes: 2

Related Questions