3

Suppose, I have a vector in PARI/GP with n elements.

I want to generate the combinations k out of n elements.

For example, if the vector is [3,7,11,14,18] and k=3, the output should be

[3,7,11]
[3,7,14]
[3,7,18]
[3,11,14]
[3,11,18]
[3,14,18]
[7,11,14]
[7,11,18]
[7,14,18]
[11,14,18]

Is there a command in PARI/GP doing this, or do I have to program the funtion ?

Piotr Semenov
  • 1,761
  • 16
  • 24
Peter
  • 214
  • 1
  • 10

2 Answers2

5

Unfortunately, PARI has not a built-in command that does all the stuff you need.

Function forvec (with flag = 2) fits the combinatorial problems very nice. So your function can be as follows:

subsets(A, k) = {
   my (lst = List());
   forvec(v = vector(k, i, [1, #A]), listput(lst, vecextract(A, v)), 2);

   Vec(lst)
};

subsets([3,7,11,14,18], 3)
gp> [[3,7,11], [3,7,14], [3,7,18], [3,11,14], [3,11,18], [3,14,18], [7,11,14], [7,11,18],
     [7,14,18], [11,14,18]]
Piotr Semenov
  • 1,761
  • 16
  • 24
2

From PARI-2.11 on, there's a more idiomatic (and faster) solution:

? v = [3,7,11,14,18]
? forsubset([#v,3], s, print(vecextract(v,s)))
[3, 7, 11]
[3, 7, 14]
[3, 7, 18]
[3, 11, 14]
[3, 11, 18]
[3, 14, 18]
[7, 11, 14]
[7, 11, 18]
[7, 14, 18]
[11, 14, 18]
K.B.
  • 861
  • 5
  • 14